打开文件作为读/写(如果存在)或不存在的最佳方法是什么,然后创建它并将其作为读/写打开?从我读到的,file = open('myfile.dat', 'rw')
应该这样做,对吗?
它不适合我(Python 2.6.2),我想知道它是否是一个版本问题,或者不应该像那样或什么工作。
最重要的是,我只需要解决问题的方法。我很好奇其他的东西,但我需要的只是一个很好的方式来做开场部分。
更新:封闭目录可由用户和组写入,而不是其他(我在Linux系统上...所以权限775换句话说),确切的错误是:
IOError:没有这样的文件或目录。
你应该使用open
和w+
模式:
file = open('myfile.dat', 'w+')
你想用文件做什么?只写它或者同时读写?
'w','a'将允许写入,如果文件不存在,将创建该文件。
如果需要从文件中读取,则必须在打开文件之前存在该文件。您可以在打开它之前测试它的存在或使用try / except。
将w +写入文件,截断(如果存在),r +读取文件,创建一个(如果不存在但不写入(并返回null)或+ +创建新文件或附加到现有文件)。
'''
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版]
使用:
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
上下文管理器将为您执行此操作。
如果你想打开它来读写,我假设你不想在打开它时截断它,你希望能够在打开文件后立即读取它。所以这是我正在使用的解决方案:
file = open('myfile.dat', 'a+')
file.seek(0, 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'
>>>
如果文件是二进制模式,请使用mode xb而不是xt。
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)
以下方法的优点是即使在路上引发异常,文件也会在块结束时正确关闭。它相当于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。
好的做法是使用以下内容:
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')
>>> import os
>>> if os.path.exists("myfile.dat"):
... f = file("myfile.dat", "r+")
... else:
... f = file("myfile.dat", "w")
r +表示读/写
将“rw”更改为“w +”
或使用“a +”进行追加(不删除现有内容)
我的答案:
file_path = 'myfile.dat'
try:
fp = open(file_path)
except IOError:
# If not exists, create the file
fp = open(file_path, 'w+')
从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)
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
。
我认为这是r +,而不是rw。我只是一个初学者,这就是我在文档中看到的。