trh*_*178 607 python linux file-io file-permissions
打开文件作为读/写(如果存在)或不存在的最佳方法是什么,然后创建它并将其作为读/写打开?从我读到的,file = open('myfile.dat', 'rw')
应该这样做,对吧?
它不适合我(Python 2.6.2),我想知道它是否是一个版本问题,或者不应该像那样或什么工作.
最重要的是,我只需要解决问题的方法.我很好奇其他的东西,但我需要的只是一个很好的方式来做开场部分.
更新:封闭目录可由用户和组写入,而不是其他(我在Linux系统上...所以权限775换句话说),确切的错误是:
IOError:没有这样的文件或目录.
小智 744
您应该使用open
与w+
模式:
file = open('myfile.dat', 'w+')
Run Code Online (Sandbox Code Playgroud)
Qwe*_*rty 122
以下方法的优点是即使在路上引发异常,文件也会在块结束时正确关闭.它相当于try-finally
,但更短.
with open("file.dat","a+") as f:
f.write(...)
...
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
只允许使用"rwab +"字符; 必须有一个"rwa" - 请参阅Stack Overflow问题Python文件模式的详细信息.
lol*_*ter 29
好的做法是使用以下内容:
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')
Run Code Online (Sandbox Code Playgroud)
Kho*_*rak 27
>>> import os
>>> if os.path.exists("myfile.dat"):
... f = file("myfile.dat", "r+")
... else:
... f = file("myfile.dat", "w")
Run Code Online (Sandbox Code Playgroud)
r +表示读/写
Chi*_*ang 12
我的答案:
file_path = 'myfile.dat'
try:
fp = open(file_path)
except IOError:
# If not exists, create the file
fp = open(file_path, 'w+')
Run Code Online (Sandbox Code Playgroud)
用:
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
Run Code Online (Sandbox Code Playgroud)
注意:打开文件后必须关闭文件,而with上下文管理器是让 Python 为您处理这个问题的好方法。
'''
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
'''
Run Code Online (Sandbox Code Playgroud)
例:
file_name = 'my_file.txt'
f = open(file_name, 'w+') # open file in write mode
f.write('python rules')
f.close()
Run Code Online (Sandbox Code Playgroud)
我希望这有帮助.[仅供参考使用python版本3.6.2
从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)
Run Code Online (Sandbox Code Playgroud)
目录相同:
filename.mkdir(parents=True, exist_ok=True)
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
它在python-2.6中引发IOError
.
你想用文件做什么?只写它或者同时读写?
'w','a'将允许写入,如果文件不存在,将创建该文件.
如果需要从文件中读取,则必须在打开文件之前存在该文件.您可以在打开它之前测试它的存在或使用try/except.
对于 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(...)
Run Code Online (Sandbox Code Playgroud)
因此,问题是with open
无法在目标目录存在之前创建文件。我们需要创建它,然后w
模式在这种情况下就足够了。
归档时间: |
|
查看次数: |
764679 次 |
最近记录: |