Python中的open()在文件不存在时不会创建文件

949 投票
18 回答
1366732 浏览
提问于 2025-04-15 23:30

怎么才能以读写的方式打开一个文件,如果这个文件不存在,就创建它并以读写的方式打开呢?我看到有人说可以用 file = open('myfile.dat', 'rw') 这样做,对吧?

可是我试了之后不行(我用的是Python 2.6.2),我在想是不是版本的问题,或者说这个方法本来就不应该这样用,或者其他什么原因。

我所在的文件夹是可以被用户和组写入的,但其他人不能(我在用Linux系统,所以权限是775),我遇到的具体错误是:

IOError: no such file or directory.

18 个回答

65
'''
w  write mode
r  read mode
a  append mode

w+  create file if it doesn't exist and open it in write mode
r+  open for reading and writing. Does not create file.
a+  create file if it doesn't exist and open it in append mode
'''

假设你现在在这个文件的工作目录里。

举个例子:

file_name = 'my_file.txt'
f = open(file_name, 'w+')  # open file in write mode
f.write('python rules')
f.close()

[顺便说一下,我使用的是Python 3.6.2版本]

203

下面这种方法的好处是,即使在执行过程中出现了错误,文件也会在代码块结束时正确关闭。这就像使用try-finally,但写起来要简单得多。

with open("file.txt","a+") as f:
    f.write("Hello world!")
    f.seek(4)
    f.readline()
    ...

a+模式是用来同时进行追加和读取文件的。如果文件已经存在,光标会在文件的末尾。如果文件不存在,它会创建一个新的文件来进行读写。-Python文件模式

seek()方法用来设置文件的当前读取位置。

例如,f.seek(4, 0) 在文件内容为 "Hello world!" 的情况下,会使得f.readline() 读取到 "o world!"

f.seek(pos [, (0|1|2)])
pos .. Number. Position of the r/w pointer
[] .. optionally
() .. one of ->
  0 .. absolute position (default)
  1 .. relative position to current
  2 .. relative position from end

只允许使用 "rwab+" 这些字符;其中必须有且只有一个 "rwa" - 具体可以参考 Stack Overflow 的问题 Python文件模式详细信息

1108

你应该使用 open 函数,并且选择 w+ 模式:

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

撰写回答