python - 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'
解决方案
你这样做是错的。
改变这个:
with(open(debug_file), 'w+') as f:
至:
with(open(debug_file, 'w+')) as f:
这与以下内容相同:
with open(debug_file, 'w+') as f:
推荐阅读
- fish - 绑定到 Fish shell 中某个键的功能需要我按回车键,如何避免这种情况?
- sql - Postgres SUM 帮助(不像预期的那样)
- elixir - 如何使用 ecto 计算 2 列值
- android - 警告:Android SDK 未安装或配置不正确
- regex - nginx 用多个反向引用重写正则表达式
- javascript - 阻止人们在发布请求中破解游戏分数的最佳方法
- java - Guava:图形的复制构造函数
- python - 从循环中的列表中删除元素
- python - 无法删除 Bokeh Server 中的回调(ValueError:回调已运行或已删除,无法再次删除)
- python - 即使安装了熊猫模块也无法运行