sourcecode

pathlib가 있는 새 폴더를 만들고 파일을 해당 폴더에 씁니다.

codebag 2023. 5. 23. 21:51
반응형

pathlib가 있는 새 폴더를 만들고 파일을 해당 폴더에 씁니다.

저는 다음과 같은 일을 하고 있습니다.

import pathlib

p = pathlib.Path("temp/").mkdir(parents=True, exist_ok=True)

with p.open("temp."+fn, "w", encoding ="utf-8") as f:
    f.write(result)

오류 메시지:특성 오류: 'NoneType' 개체에 'open' 특성이 없습니다.

분명히, 오류 메시지에 따르면,mkdir돌아온다None.

장 프랑수아 파브르는 다음과 같은 수정을 제안했습니다.

p = pathlib.Path("temp/")
p.mkdir(parents=True, exist_ok=True)

with p.open("temp."+fn, "w", encoding ="utf-8") as f:
    ...

새 오류 메시지가 트리거되었습니다.

파일 "/Users/user/anaconda/lib/python3.6/pathlib.py ", 행 1164, openoper=self._filename)
유형 오류: 정수가 필요합니다(str 유형 가져오기).

시도해 볼 수 있습니다.

p = pathlib.Path("temp/")
p.mkdir(parents=True, exist_ok=True)
fn = "test.txt" # I don't know what is your fn
filepath = p / fn
with filepath.open("w", encoding ="utf-8") as f:
    f.write(result)

문자열을 경로로 지정하면 안 됩니다.그것은 당신의 목적입니다.filepath방법이 있는 것.open.

원천

직접 초기화할 수 있습니다.filepath의 상위 디렉토리 생성parent속성:

from pathlib import Path

filepath = Path("temp/test.txt")
filepath.parent.mkdir(parents=True, exist_ok=True)

with filepath.open("w", encoding ="utf-8") as f:
    f.write(result)

아마도 이것이 당신이 하고 싶은 가장 짧은 코드일 것입니다.

import pathlib

p = pathlib.Path("temp/")
p.mkdir(parents=True, exist_ok=True)
(p / ("temp." + fn)).write_text(result, encoding="utf-8")

대부분의 경우 write_text()를 대신 사용하여 open() 컨텍스트도 필요하지 않습니다.

pathlib 모듈은 다음을 제공합니다.open기본 제공 오픈 함수와 서명이 약간 다른 메서드입니다.

pathlib:

Path.open(mode='r', buffering=-1, encoding=None, errors=None, newline=None)

기본 제공:

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

이 경우에는p = pathlib.Path("temp/")그것은 길을 만들었습니다.p소콜링p.open("temp."+fn, "w", encoding ="utf-8")(키워드를 사용하지 않는) 위치 인수를 사용하여 첫 번째가 될 것으로 예상합니다.mode,그리고나서buffering,그리고.buffering정수를 예상합니다. 이것이 오류의 본질입니다. 정수가 예상되지만 문자열을 수신했습니다.'w'.

이 통화p.open("temp."+fn, "w", encoding ="utf-8")길을 열려고 하는 중입니다.p(디렉토리) 및 지원되지 않는 파일 이름을 제공합니다.전체 경로를 구성한 다음 경로의 열린 메서드를 호출하거나 전체 경로를 열린 내장 함수로 전달해야 합니다.

다음과 같은 작업도 수행할 수 있습니다.

text_path = Path("random/results").resolve()
text_path.mkdir(parents=True, exist_ok=True)
(text_path / f"{title}.txt").write_text(raw_text)

언급URL : https://stackoverflow.com/questions/47518669/create-new-folder-with-pathlib-and-write-files-into-it

반응형