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

1586010002-jmsa.png

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)

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值