如果文件不存在,Python中的open()不会创建文件

时间:2010-06-03 15:05:54

标签: python linux file-io file-permissions

如果文件存在,或者如果不存在,则将文件作为读/写打开的最佳方法是什么,然后创建它并将其作为读/写打开?根据我的阅读,file = open('myfile.dat', 'rw')应该这样做,对吗?

它对我不起作用(Python 2.6.2),我想知道它是否是版本问题,或者不应该像那样或者什么工作。

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

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

  

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

17 个答案:

答案 0 :(得分:712)

您应该open使用w+模式:

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

答案 1 :(得分:112)

以下方法的优点是,即使在路上引发异常,文件在块结尾处正确关闭。它相当于try-finally,但更短。

with open("file.dat","a+") as f:
    f.write(...)
    ...
  

a + 打开附加和读取的文件。文件指针是   如果文件存在,则在文件末尾。该文件打开   追加模式。如果该文件不存在,则为其创建新文件   读写。 - Python file modes

seek() method设置文件的当前位置。

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

只允许使用“rwab +”字符;必须有一个“rwa” - 请参阅Stack Overflow问题 Python file modes detail

答案 2 :(得分:32)

良好做法是使用以下内容:

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')

答案 3 :(得分:31)

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

r +表示读/写

答案 4 :(得分:26)

将“rw”改为“w +”

或使用'a +'附加(不删除现有内容)

答案 5 :(得分:14)

我的回答:

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

答案 6 :(得分:7)

open('myfile.dat', 'a')对我有用,很好。

在py3k中,您的代码会引发ValueError

>>> open('myfile.dat', 'rw')
Traceback (most recent call last):
  File "<pyshell#34>", line 1, in <module>
    open('myfile.dat', 'rw')
ValueError: must have exactly one of read/write/append mode

在python-2.6中它引发了IOError

答案 7 :(得分:7)

从python 3.4起,你应该使用pathlib来“触摸”文件 它比这个帖子中提出的解决方案更优雅。

from pathlib import Path

filename = Path('myfile.txt')
filename.touch(exist_ok=True)  # will create file, if it exists will do nothing
file = open(filename)

与目录相同:

filename.mkdir(parents=True, exist_ok=True)

答案 8 :(得分:6)

你想用文件做什么?只写它或者同时读写?

'w','a'将允许写入,如果文件不存在,将创建该文件。

如果您需要从文件中读取,则必须在打开文件之前存在该文件。您可以在打开它之前测试它的存在或使用try / except。

答案 9 :(得分:6)

我认为它是 r + ,而不是 rw 。我只是一个初学者,这就是我在文档中看到的。

答案 10 :(得分:5)

对于 Python 3+,我会这样做:

import os

os.makedirs('path/to/the/directory', exist_ok=True)

with open('path/to/the/directory/filename', 'w') as f:
    f.write(...)

所以,问题是 with open 无法在目标目录存在之前创建文件。我们需要创建它,然后在这种情况下 w 模式就足够了。

答案 11 :(得分:5)

'''
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]

答案 12 :(得分:5)

将w +写入文件,截断(如果存在),r +读取文件,创建一个如果不存在但不写入(并返回null)或+ +用于创建新文件或附加到文件现有的。

答案 13 :(得分:4)

如果你想打开它进行读写,我假设你不想在打开它时截断它,你希望能够在打开文件后立即读取它。所以这就是我正在使用的解决方案:

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

答案 14 :(得分:4)

使用:

import os

f_loc = r"C:\Users\Russell\Desktop\ip_addr.txt"

if not os.path.exists(f_loc):
    open(f_loc, 'w').close()

with open(f_loc) as f:
    #Do stuff

确保在打开文件后关闭文件。 with上下文管理器会为您执行此操作。

答案 15 :(得分:1)

import os, platform
os.chdir('c:\\Users\\MS\\Desktop')

try :
    file = open("Learn Python.txt","a")
    print('this file is exist')
except:
    print('this file is not exist')
file.write('\n''Hello Ashok')

fhead = open('Learn Python.txt')

for line in fhead:

    words = line.split()
print(words)

答案 16 :(得分:0)

所以你想把数据写入文件,但只有它还不存在?

通过使用鲜为人知的x模式来打开()而不是通常的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。