如果文件存在或不存在,那么以读/写方式打开文件的最佳方法是什么,然后创建它并以读/写方式打开它?根据我的阅读,file = open('myfile.dat', 'rw')
应该这样做,对吧?
它对我不起作用(Python 2.6.2),我想知道这是否是版本问题,或者不应该像那样工作或什么。
最重要的是,我只需要一个解决问题的方法。我对其他的东西很好奇,但我需要的只是一个很好的方法来做开头部分。
封闭目录可由用户和组写入,而不是其他(我在 Linux 系统上......所以权限 775 换句话说),确切的错误是:
IOError:没有这样的文件或目录。
file
的所有前导文件夹都存在。
您应该将 open
与 w+
模式一起使用:
file = open('myfile.dat', 'w+')
以下方法的优点是文件在块的末尾正确关闭,即使在途中引发异常也是如此。它相当于 try-finally
,但要短得多。
with open("file.dat","a+") as f:
f.write(...)
...
a+ 打开一个文件以进行追加和读取。如果文件存在,则文件指针位于文件末尾。该文件以附加模式打开。如果该文件不存在,则创建一个新文件进行读写。 -Python 文件模式
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 文件模式详细信息。
filename
的值吗?
'''
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
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')
将“rw”更改为“w+”
或使用 'a+' 追加(不删除现有内容)
>>> import os
>>> if os.path.exists("myfile.dat"):
... f = file("myfile.dat", "r+")
... else:
... f = file("myfile.dat", "w")
r+ 表示读/写
从 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)
touch
在使用时会更新上次修改时间。
touch
时也是如此,所以我认为这是预期的行为。
我的答案:
file_path = 'myfile.dat'
try:
fp = open(file_path)
except IOError:
# If not exists, create the file
fp = open(file_path, 'w+')
利用:
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 上下文管理器是让 Python 为您处理此问题的好方法。
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
。
对于 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
模式就足够了。
你想对文件做什么?只写它还是读写?
'w'
、'a'
将允许写入并在文件不存在时创建文件。
如果您需要从文件中读取,则该文件必须在打开之前存在。您可以在打开它之前测试它的存在或使用 try/except。
我认为是 r+
,而不是 rw
。我只是一个初学者,这就是我在文档中看到的。
将 w+ 用于写入文件,如果存在则截断, r+ 用于读取文件,如果文件不存在则创建一个但不写入(并返回 null)或 a+ 用于创建新文件或附加到现有文件。
如果您想打开它进行读写,我假设您不想在打开它时截断它,并且希望能够在打开文件后立即读取文件。所以这是我正在使用的解决方案:
file = open('myfile.dat', 'a+')
file.seek(0, 0)
因此,您想将数据写入文件,但前提是它尚不存在?
这个问题很容易通过使用鲜为人知的 x 模式来 open() 而不是通常的 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。
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)
不定期副业成功案例分享
w
截断现有文件。 docs:模式'r+'
、'w+'
和'a+'
打开文件进行更新(注意'w+'
会截断文件)。open('myfile.dat', 'w')
就足够了。