【发布时间】:2017-10-10 19:09:06
【问题描述】:
在 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...
【问题讨论】:
-
总是添加通用的python标签,顺便说一句
-
@juanpa.arrivillaga 好点;欣赏它!
-
嗯,你不能只使用
'a+'模式,如果它不存在,它将创建它,并将流定位在末尾? -
@juanpa.arrivillaga 使用 f.seek(0),对吗?出于某种原因,我不喜欢它的样子,但我觉得我只是很奇怪哈哈。可能最好这样做
-
但是您是否只是从文件中读取以便可以附加到它?
标签: python python-3.x file io