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
'sourcecode' 카테고리의 다른 글
전원 쿼리:그룹화된 값을 연결하려면 어떻게 해야 합니까? (0) | 2023.05.23 |
---|---|
하위 프로세스를 사용하는 방법.파이썬에서 check_output()? (0) | 2023.05.23 |
Stuff 및 'For Xml Path'는 SQL Server에서 어떻게 작동합니까? (0) | 2023.05.23 |
Git에서 단계별 변경 사항만 저장하는 방법은 무엇입니까? (0) | 2023.05.23 |
열거형 MongoDB 저장 (0) | 2023.05.23 |