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

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

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

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

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


当前回答

Use:

import os

f_loc = r"C:\Users\Russell\Desktop\myfile.dat"

# Create the file if it does not exist
if not os.path.exists(f_loc):
    open(f_loc, 'w').close()

# Open the file for appending and reading
with open(f_loc, 'a+') as f:
    #Do stuff

注意:文件在打开后必须关闭,而with context管理器是让Python为你处理这一问题的好方法。

其他回答

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

R +表示读/写

Use:

import os

f_loc = r"C:\Users\Russell\Desktop\myfile.dat"

# Create the file if it does not exist
if not os.path.exists(f_loc):
    open(f_loc, 'w').close()

# Open the file for appending and reading
with open(f_loc, 'a+') as f:
    #Do stuff

注意:文件在打开后必须关闭,而with context管理器是让Python为你处理这一问题的好方法。

你应该在w+模式下使用open:

file = open('myfile.dat', 'w+')

好的做法是使用以下方法:

import os

writepath = 'some/path/to/file.txt'

mode = 'a' if os.path.exists(writepath) else 'w'
with open(writepath, mode) as f:
    f.write('Hello, world!\n')

输入w+表示写入文件,如果文件存在则截断,r+表示读取文件,如果文件不存在则创建一个文件但不写入(并返回null),或者输入+表示创建新文件或追加到现有文件。