Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

python - 如果不存在,则Python中的open()不会创建文件(open() in Python does not create a file if it doesn't exist)

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?

(根据我的阅读, file = open('myfile.dat', 'rw')应该这样做,对吗?)

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.

(它对我不起作用(Python 2.6.2),我想知道这是否是版本问题,或者不应该那样工作或做什么。)

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.

(我对其他东西很好奇,但是我所需要的只是做开始部分的好方法。)

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:

(封闭目录可由用户和组而非其他用户(我在Linux系统上...因此权限775)可写,确切的错误是:)

IOError: no such file or directory.

(IOError:没有这样的文件或目录。)

  ask by trh178 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

您应该在w+模式下使用open

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...