使用pathlib在python中创建新文件夹并将文件写入其中 [英] create new folder in python with pathlib and write files into it

查看:2988
本文介绍了使用pathlib在python中创建新文件夹并将文件写入其中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做这样的事情:

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'

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

很明显,根据错误消息,mkdir返回None.

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

Jean-Francois Fabre建议进行以下更正:

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:

文件"/Users/user/anaconda/lib/python3.6/pathlib.py",第1164行,处于打开状态 opener = self._opener)
TypeError:必须为整数(类型为str)

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

推荐答案

pathlib 模块提供了一个open方法,该方法的签名与内置的打开功能.

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)

内置:

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,然后是bufferingbuffering期望一个整数,这就是错误的本质;需要一个整数,但它接收到字符串'w'.

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'.

此调用p.open("temp."+fn, "w", encoding ="utf-8")试图打开路径p(这是目录),并且还提供了不支持的文件名.您必须构造完整路径,然后调用路径的open方法或将完整路径传递到开放的内置函数中.

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.

这篇关于使用pathlib在python中创建新文件夹并将文件写入其中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆