Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如果文件不存在,则创建文件';t存在,然后以RW模式打开文件_Python_Python 3.x_File_Io - Fatal编程技术网

Python 如果文件不存在,则创建文件';t存在,然后以RW模式打开文件

Python 如果文件不存在,则创建文件';t存在,然后以RW模式打开文件,python,python-3.x,file,io,Python,Python 3.x,File,Io,在Python中,我试图创建一个不存在的文件,然后以读/写模式打开它。我能用以下最简洁的方式表达这一点: with os.fdopen(os.open('foo.bar', os.O_RDWR | os.O_CREAT), "r+") as f: # read file contents... # append new stuff... 有更好的方法吗?如果不是os.path.exists('foo.bar'),我应该只检查,如果不存在,创建文件,然后以“r+”模式打开文件吗

在Python中,我试图创建一个不存在的文件,然后以读/写模式打开它。我能用以下最简洁的方式表达这一点:

with os.fdopen(os.open('foo.bar', os.O_RDWR | os.O_CREAT), "r+") as f:
    # read file contents...
    # append new stuff...
有更好的方法吗?如果不是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")
否则,按建议执行:

with open("filename", "a+") as f
  f.write("Hello, world")

“a+”打开文件并从文件末尾开始。查看以了解更多有关如何工作的信息。

第二个选项有点不确定,因为如果您的程序不是该文件的唯一用户/使用者,则在打开前进行测试会使您面临竞争条件

我可能会使用+并从头开始查找

with open("file", "a+") as f:
    f.seek(0)
    f.read()
    ...
<> P>文件中的其他东西,我想是直接丢弃Python文件对象,直接使用OS。
fd = os.open("file", os.O_RDWR | os.O_CREAT)
buffer = os.read(fd)
new_data = b'stuff to append'
os.write(fd, new_data)
os.close(fd)

etc

这将需要更多的代码,因为您必须手动跟踪文件句柄,这可能比使用“with”上下文管理更痛苦

始终添加通用python标记,btw@juanpa.arrivillaga好的观点;谢谢你!嗯,你能不能只使用
'a+'
模式,如果它不存在,将创建它,并将流定位在末尾?@juanpa.arrivillaga使用f.seek(0),对吗?出于某种原因,我不喜欢它看起来的样子,但我觉得我很奇怪,哈哈。也许最好这样做,但你只是从文件中读取,以便可以附加到它吗?