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

查看:2373
本文介绍了Python中的open()不会创建文件,如果它不存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果文件存在或者不存在,将文件打开为读/写的最佳方式是什么?然后创建并以读/写方式打开文件?从我读的, file = open('myfile.dat','rw')应该这样做,对吧?

它不适用于我(Python 2.6.2),我想知道它是否是一个版本问题,或不应该像这样或那样工作。

<底线是,我只需要解决这个问题。我很好奇其他的东西,但是我需要的只是一个很好的方式来做开头部分。
$ b $ p

更新:封闭的目录可以被用户和组写入,而不是其他(我在Linux系统上...所以权限775换句话说),确切的错误是:
$ b


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



解决方案打开('myfile.dat','w +')


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?

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.

UPDATE: 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: no such file or directory.

解决方案

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

这篇关于Python中的open()不会创建文件,如果它不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆