在Python中,如果文件不存在,我尝试创建一个文件,然后以读/写模式打开它。我能够表达这一点的最简洁的方式如下:
with os.fdopen(os.open('foo.bar', os.O_RDWR | os.O_CREAT), "r+") as f:
# read file contents...
# append new stuff...
有更好的方法吗?我是否应该检查 if not os.path.exists('foo.bar')
,如果文件不存在则创建该文件,然后以“r+”模式打开该文件?
本质上:
if not os.path.exists('foo.bar'):
os.makedirs('foo.bar') # or open('foo.bar', 'a').close()
with open('foo.bar', "r+") as f:
# read file contents...
# append new stuff...
最佳答案
主要问题是如果文件已经存在,您是否要截断该文件。
如果是这样,则执行以下操作:
with open("filename", "w+") as f:
f.write("Hello, world")
否则,做什么 juanpa.arrivillaga建议:
with open("filename", "a+") as f
f.write("Hello, world")
“a+”打开文件并从文件末尾开始。检查documentation了解更多关于其工作原理的信息。
关于python - 如果文件不存在则创建文件,然后以 RW 模式打开该文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46674195/