Python中的open()如果文件不存在

2024-04-27 04:00:12 发布

您现在位置:Python中文网/ 问答频道 /正文

如果文件存在,或者不存在,则以读/写方式打开该文件的最佳方法是什么?据我所读,file = open('myfile.dat', 'rw')应该这样做,对吧?

它对我(Python2.6.2)不起作用,我想知道这是不是一个版本问题,或者不应该像那样工作,或者什么。

归根结底,我只是需要一个解决问题的办法。我对其他的东西很好奇,但我只需要一个好的方法来做开场白。

封闭目录是用户和组可写的,而不是其他(我在Linux系统上。。。也就是说,权限775),准确的错误是:

IOError: no such file or directory.


Tags: 文件方法用户版本目录linux系统方式
3条回答

您应该将openw+模式一起使用:

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

将“rw”改为“w+”

或使用“a+”进行追加(不删除现有内容)

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

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() 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

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

相关问题 更多 >