如果文件以读/写方式打开,或者以不存在的方式创建,然后以读/写方式打开,最好的方法是什么? 根据我的阅读, file = open('myfile.dat', 'rw')应该这样做,对吗?
它对我不起作用(Python 2.6.2),我想知道这是否是版本问题,或者不应该那样工作或做什么。
最重要的是,我只需要解决这个问题。 我对其他东西很好奇,但是我所需要的只是做开始部分的好方法。
封闭目录可由用户和组而非其他用户(我在Linux系统上...因此权限775)可写,确切的错误是:
IOError:没有这样的文件或目录。
#1楼
以下方法的优点是,即使在执行过程中引发了异常,文件也会在块的末尾正确关闭 。 它等效于try-finally ,但是要短得多。
with open("file.dat","a+") as f:
f.write(...)
...
a +打开一个文件以进行附加和读取。 如果文件存在,则文件指针位于文件的末尾。 该文件以追加模式打开。 如果该文件不存在,它将创建一个用于读取和写入的新文件。 -Python文件模式
seek()方法设置文件的当前位置。
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问题
#2楼
我认为是r+而不是rw 。 我只是一个入门者,这就是我在文档中看到的内容。
#3楼
我的答案:
file_path = 'myfile.dat'
try:
fp = open(file_path)
except IOError:
# If not exists, create the file
fp = open(file_path, 'w+')
#4楼
使用:
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为您解决此问题的一种好方法。
#5楼
open('myfile.dat', 'a')对我open('myfile.dat', 'a') ,就好。
在py3k中,您的代码引发ValueError :
>>> open('myfile.dat', 'rw')
Traceback (most recent call last):
File "", line 1, in
open('myfile.dat', 'rw')
ValueError: must have exactly one of read/write/append mode
在python-2.6中,它引发IOError 。