如果一个文件存在,那么以读/写的方式打开它,或者如果它不存在,那么创建它并以读/写的方式打开它,最好的方法是什么?从我读到的,file = open('myfile.dat', 'rw')应该这样做,对吗?

它不适合我(Python 2.6.2),我想知道这是版本问题,还是不应该这样工作或其他什么。

最重要的是,我只需要一个解决问题的办法。我对其他的东西很好奇,但我只需要一个好方法来做开头部分。

封闭的目录可由用户和组写入,而不是其他(我在Linux系统上…所以权限775换句话说),准确的错误是:

IOError:没有这样的文件或目录。


当前回答

所以你想写数据到一个文件,但只有当它还不存在?。

这个问题很容易通过使用鲜为人知的x模式来open()而不是通常的w模式来解决。例如:

 >>> with open('somefile', 'wt') as f:
 ...     f.write('Hello\n')
...
>>> with open('somefile', 'xt') as f:
...     f.write('Hello\n')
...
 Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
FileExistsError: [Errno 17] File exists: 'somefile'
  >>>

如果文件是二进制模式,则使用模式xb而不是xt。

其他回答

我的回答:

file_path = 'myfile.dat'
try:
    fp = open(file_path)
except IOError:
    # If not exists, create the file
    fp = open(file_path, 'w+')

如果你想打开它来读写,我假设你不想在打开它的时候截断它,你想在打开它之后能够读取文件。这就是我使用的解决方案:

file = open('myfile.dat', 'a+')
file.seek(0, 0)

所以你想写数据到一个文件,但只有当它还不存在?。

这个问题很容易通过使用鲜为人知的x模式来open()而不是通常的w模式来解决。例如:

 >>> with open('somefile', 'wt') as f:
 ...     f.write('Hello\n')
...
>>> with open('somefile', 'xt') as f:
...     f.write('Hello\n')
...
 Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
FileExistsError: [Errno 17] File exists: 'somefile'
  >>>

如果文件是二进制模式,则使用模式xb而不是xt。

将rw改为w+

或者使用'a+'追加(而不是删除现有内容)

>>> import os
>>> if os.path.exists("myfile.dat"):
...     f = file("myfile.dat", "r+")
... else:
...     f = file("myfile.dat", "w")

R +表示读/写