如果文件不存在,Python 中的 open() 不会创建文件 [英] open() in Python does not create a file if it doesn't exist
问题描述
如果文件存在,以读/写方式打开文件的最佳方法是什么,或者如果不存在,则创建它并以读/写方式打开它?根据我的阅读,file = open('myfile.dat', 'rw')
应该这样做,对吗?
What is the best way to open a file as read/write if it exists, or if it does not, then create it and open it as read/write? From what I read, file = open('myfile.dat', 'rw')
should do this, right?
它对我不起作用(Python 2.6.2),我想知道这是不是版本问题,或者不应该像那样工作或什么.
It is not working for me (Python 2.6.2) and I'm wondering if it is a version problem, or not supposed to work like that or what.
最重要的是,我只需要一个解决问题的方法.我对其他东西很好奇,但我只需要一个很好的方式来做开场部分.
The bottom line is, I just need a solution for the problem. I am curious about the other stuff, but all I need is a nice way to do the opening part.
封闭目录可由用户和组写入,而不是其他(我在 Linux 系统上...所以权限 775 换句话说),确切的错误是:
The enclosing directory was writeable by user and group, not other (I'm on a Linux system... so permissions 775 in other words), and the exact error was:
IOError: 没有那个文件或目录.
IOError: no such file or directory.
推荐答案
你应该使用 open
和 w+
模式:
You should use open
with the w+
mode:
file = open('myfile.dat', 'w+')
这篇关于如果文件不存在,Python 中的 open() 不会创建文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!