Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

create new folder in python with pathlib and write files into it

I'm doing something like this:

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)

Error message: AttributeError: 'NoneType' object has no attribute 'open'

Obviously, based on the error message, mkdir returns None.

Jean-Francois Fabre suggested this correction:

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

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

This triggered a new error message:

File "/Users/user/anaconda/lib/python3.6/pathlib.py", line 1164, in open opener=self._opener)
TypeError: an integer is required (got type str)

question from:https://stackoverflow.com/questions/47518669/create-new-folder-in-python-with-pathlib-and-write-files-into-it

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The pathlib module offers an open method that has a slightly different signature to the built-in open function.

pathlib:

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

The built-in:

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

In the case of this p = pathlib.Path("temp/") it has created a path p so calling p.open("temp."+fn, "w", encoding ="utf-8") with positional arguments (not using keywords) expects the first to be mode, then buffering, and buffering expects an integer, and that is the essence of the error; an integer is expected but it received the string 'w'.

This call p.open("temp."+fn, "w", encoding ="utf-8") is trying to open the path p (which is a directory) and also providing a filename which isn't supported. You have to construct the full path, and then either call the path's open method or pass the full path into the open built-in function.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...