使用pathlib在python中创建新文件夹并将文件写入其中

时间:2017-11-27 19:45:36

标签: python-3.x 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)
  

错误消息:AttributeError:'NoneType'对象没有属性'open'

显然,根据错误消息,mkdir会返回None

Jean-Francois Fabre提出了这一更正:

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行,处于打开状态       开瓶器= self._opener)
  TypeError:需要一个整数(得到类型str)

4 个答案:

答案 0 :(得分:19)

你可以尝试:

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

source

答案 1 :(得分:8)

您可以直接初始化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)

答案 2 :(得分:5)

也许这是您想要做的最短的代码。

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()上下文。

答案 3 :(得分:2)

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.