首页 > 解决方案 > Python open 不会根据文档创建文件

问题描述

我很难相信 python 在 2020 年仍然存在创建文件的问题......所以,我假设它是 windows 或我......

这是带有输出的代码。

我尝试了 w、w+、wt 模式,错误消息如下。使用 w, w+, wt 的全部意义在于如果文件不存在则创建该文件

我已更改为使用 Path.touch,然后使用仅给出和错误输入的 a、a+ 模式


import sys
print("Python version:")
print (sys.version)

import platform
print("Platform: {} - {} - {}".format(platform.system(), platform.release(), platform.version()))

from pathlib import Path
output = 'hello world!'
save_dir = Path.cwd().joinpath("./sw_out")
if(save_dir.exists() == False):
    save_dir.mkdir()
    print("dir exists now: {}".format(save_dir.exists()))

debug_file = save_dir.joinpath("my_debug.txt")
#debug_file.touch(exist_ok=True)
print(str(debug_file))
with(open(debug_file), 'w+') as f:
    f.write(output)
f.close()
Python version:
3.7.6 | packaged by conda-forge | (default, Dec 26 2019, 23:30:11) [MSC v.1916 64 bit (AMD64)]
Platform: Windows - 10 - 10.0.17763
dir exists now: True
C:\users\me\project\sw_out\my_debug.txt

---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-19-447d2a994262> in <module>
     16 #debug_file.touch(exist_ok=True)
     17 print(str(debug_file))
---> 18 with(open(str(debug_file)), 'w+') as f:
     19     f.write(output)
     20 f.close()

FileNotFoundError: [Errno 2] No such file or directory: 'C:\\users\\me\\project\\sw_out\\my_debug.txt'

标签: python

解决方案


你这样做是错的。

改变这个:

with(open(debug_file), 'w+') as f:

至:

with(open(debug_file, 'w+')) as f:

这与以下内容相同:

with open(debug_file, 'w+') as f:

推荐阅读