关于Linux:python中的open()如果文件不存在,则不会创建该文件

open() in Python does not create a file if it doesn't exist

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

它不适用于我(python 2.6.2),我想知道它是否是一个版本问题,或者不应该像那样工作。

底线是,我只需要一个问题的解决方案。我对其他的东西很好奇,但我所需要的是一个很好的方式来做开场白。

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

IOError: no such file or directory.


您应该使用openw+模式:

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


以下方法的优点是,即使在运行过程中引发异常,文件也会在块的末尾正确关闭。它相当于try-finally,但短得多。

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

a+ Opens a file for both appending and reading. The file pointer is
at the end of the file if the file exists. The file opens in the
append mode. If the file does not exist, it creates a new file for
reading and writing. -Python file modes

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

1
2
3
4
5
6
7
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

Only"rwab+" characters are allowed; there must be exactly one of"rwa" - see Stack Overflow question Python file modes detail.


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

1
2
3
4
5
6
7
8
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!
'
)


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

R+表示读/写


将"rw"改为"w+"

或使用"a+"追加(不删除现有内容)


我的回答是:

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


江户十一〔0〕为我工作,很好。

在py3k中,您的代码引发ValueError

1
2
3
4
5
>>> 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


您希望如何处理文件?只写还是读写?

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

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


我想是r+,不是rw。我只是个初学者,这就是我在文档中看到的。


由于python 3.4,您应该使用pathlib来"触摸"文件。这是一个比本文中建议的更优雅的解决方案。

1
2
3
4
5
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)

与目录相同:

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

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


1
2
3
4
5
6
7
8
9
'''
w  write mode
r  read mode
a  append mode

w+  create file if it doesn't exist and open it in write mode
r+  create file if it doesn't exist and open it in read mode
a+  create file if it doesn't exist and open it in append mode
'''

例子:

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

我希望这有帮助。[fyi正在使用python 3.6.2版


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

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

用途:

1
2
3
4
5
6
7
8
9
10
import os

f_loc = r"C:\Users
ussell\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上下文管理器将为您执行此操作。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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('
'
'Hello Ashok')

fhead = open('Learn Python.txt')

for line in fhead:

    words = line.split()
print(words)

所以你想把数据写到一个文件中,但前提是它不存在?.

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

1
2
3
4
5
6
7
8
9
10
11
12
 >>> with open('somefile', 'wt') as f:
 ...     f.write('Hello
'
)
...
>>> with open('somefile', 'xt') as f:
...     f.write('Hello
'
)
...
 Traceback (most recent call last):
 File"<stdin>", line 1, in <module>
FileExistsError: [Errno 17] File exists: 'somefile'
  >>>

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