Linux 如果文件不存在,Python 中的 open() 不会创建文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2967194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 20:06:05  来源:igfitidea点击:

open() in Python does not create a file if it doesn't exist

pythonlinuxfile-iofile-permissions

提问by trh178

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: 没有这样的文件或目录。

采纳答案by muksie

You should use openwith the w+mode:

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

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

回答by SilentGhost

open('myfile.dat', 'a')works for me, just fine.

open('myfile.dat', 'a')对我有用,很好。

in py3k your code raises ValueError:

在 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

in python-2.6 it raises IOError.

在 python-2.6 中,它引发了IOError.

回答by baloo

Change "rw" to "w+"

将“rw”更改为“w+”

Or use 'a+' for appending (not erasing existing content)

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

回答by Khorkrak

>>> import os
>>> if os.path.exists("myfile.dat"):
...     f = file("myfile.dat", "r+")
... else:
...     f = file("myfile.dat", "w")

r+ means read/write

r+ 表示读/写

回答by user49117

What do you want to do with file? Only writing to it or both read and write?

你想用文件做什么?只写它还是既读又写?

'w', 'a'will allow write and will create the file if it doesn't exist.

'w','a'将允许写入并在文件不存在时创建该文件。

If you need to read from a file, the file has to be exist before open it. You can test its existence before opening it or use a try/except.

如果您需要从文件中读取,则该文件必须存在才能打开。您可以在打开它之前测试它的存在或使用 try/except。

回答by Qwerty

The advantage of the following approach is that the file is properly closedat the block's end, even if an exception is raised on the way. It's equivalent to try-finally, but much shorter.

以下方法的优点是文件在块的末尾被正确关闭,即使在途中引发异常。它相当于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

a+打开一个文件进行追加和读取。如果文件存在,则文件指针位于文件末尾。文件以追加模式打开。如果文件不存在,它会创建一个新文件进行读写。- Python 文件模式

seek() methodsets the file's current position.

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

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

只允许使用“rwab+”字符;必须恰好是“rwa”之一 - 请参阅堆栈溢出问题Python 文件模式详细信息

回答by Angel Poppy

I think it's r+, not rw. I'm just a starter, and that's what I've seen in the documentation.

我认为是r+,不是rw。我只是一个初学者,这就是我在文档中看到的。

回答by Chien-Wei Huang

My answer:

我的答案:

file_path = 'myfile.dat'
try:
    fp = open(file_path)
except IOError:
    # If not exists, create the file
    fp = open(file_path, 'w+')

回答by wp-overwatch.com

Use:

用:

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

Note: Files have to be closed after you open them, and the withcontext manager is a nice way of letting Python take care of this for you.

注意:打开文件后必须关闭文件,而with上下文管理器是让 Python 为您处理这个问题的好方法。

回答by lollercoaster

Good practice is to use the following:

好的做法是使用以下内容:

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