简体   繁体   English

如果文件不存在,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: 没有这样的文件或目录。

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

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

The advantage of the following approach is that the file is properly closed at 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. a+打开一个文件进行追加和读取。 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 - Python 文件模式

seek() method sets 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;只允许使用“rwab+”字符; there must be exactly one of "rwa" - see Stack Overflow question Python file modes detail .必须恰好是“rwa”之一 - 请参阅堆栈溢出问题Python 文件模式详细信息

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

Change "rw" to "w+"将“rw”更改为“w+”

Or use 'a+' for appending (not erasing existing content)或使用“a+”进行附加(不删除现有内容)

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

r+ means read/write r+ 表示读/写

'''
w  write mode
r  read mode
a  append mode

w+  create file if it doesn't exist and open it in write mode
r+  open for reading and writing. Does not create file.
a+  create file if it doesn't exist and open it in append mode
'''

example:例子:

file_name = 'my_file.txt'
f = open(file_name, 'w+')  # open file in write mode
f.write('python rules')
f.close()

[FYI am using Python version 3.6.2] [仅供参考,我使用的是 Python 3.6.2 版]

Since python 3.4 you should use pathlib to "touch" files.从 python 3.4 开始,您应该使用pathlib来“触摸”文件。
It is a much more elegant solution than the proposed ones in this thread.这是一个比这个线程中提出的解决方案更优雅的解决方案。

from pathlib import Path

filename = Path('myfile.txt')
filename.touch(exist_ok=True)  # will create file, if it exists will do nothing
file = open(filename)

Same thing with directories:与目录相同的事情:

filename.mkdir(parents=True, exist_ok=True)

My answer:我的答案:

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

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 with context manager is a nice way of letting Python take care of this for you.注意:打开文件后必须将其关闭,而with上下文管理器是让 Python 为您处理此问题的好方法。

I think it's r+ , not rw .我认为是r+ ,而不是rw I'm just a starter, and that's what I've seen in the documentation.我只是一个初学者,这就是我在文档中看到的。

open('myfile.dat', 'a') works for me, just fine. open('myfile.dat', 'a')对我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

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。

For Python 3+, I will do:对于 Python 3+,我会这样做:

import os

os.makedirs('path/to/the/directory', exist_ok=True)

with open('path/to/the/directory/filename', 'w') as f:
    f.write(...)

So, the problem is with open cannot create a file before the target directory exists.因此,问题是with open无法在目标目录存在之前创建文件。 We need to create it and then w mode is enough in this case.我们需要创建它,然后w模式在这种情况下就足够了。

将 w+ 用于写入文件,如果存在则截断,r+ 用于读取文件,如果文件不存在则创建一个但不写入(并返回 null)或 a+ 用于创建新文件或附加到现有文件。

If you want to open it to read and write, I'm assuming you don't want to truncate it as you open it and you want to be able to read the file right after opening it.如果你想打开它来读写,我假设你不想在打开它时截断它,并且你希望能够在打开文件后立即读取它。 So this is the solution I'm using:所以这是我正在使用的解决方案:

file = open('myfile.dat', 'a+')
file.seek(0, 0)

So You want to write data to a file, but only if it doesn't already exist?.所以你想将数据写入文件,但前提是它不存在?

This problem is easily solved by using the little-known x mode to open() instead of the usual w mode.这个问题很容易通过使用鲜为人知的 x 模式来 open() 而不是通常的 w 模式来解决。 For example:例如:

 >>> with open('somefile', 'wt') as f:
 ...     f.write('Hello\n')
...
>>> with open('somefile', 'xt') as f:
...     f.write('Hello\n')
...
 Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
FileExistsError: [Errno 17] File exists: 'somefile'
  >>>

If the file is binary mode, use mode xb instead of xt.如果文件是二进制模式,请使用模式 xb 而不是 xt。

If you just need a file, Use: 如果只需要一个文件,请使用:

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

usually there might be reminder to declear that the file doesn't exists and you make a new one. 通常,可能会提醒您清除该文件不存在,并重新创建一个文件。 Use: 采用:

try:
    file = open('myfile.dat')
except:
    print("the file doesn't exists, make a new one")
    file = open('myfile.dat', 'w+')
import os, platform
os.chdir('c:\\Users\\MS\\Desktop')

try :
    file = open("Learn Python.txt","a")
    print('this file is exist')
except:
    print('this file is not exist')
file.write('\n''Hello Ashok')

fhead = open('Learn Python.txt')

for line in fhead:

    words = line.split()
print(words)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 python open说文件不存在 - Python open says file doesn't exist when it does Python ConfigParser - 如果不存在则创建文件 - Python ConfigParser - Create File if it Doesn't Exist 如何打开文件进行读写,如果不存在则创建它,如果存在,则不截断它? - How to open a file for reading and writing, create it if doesn't exist yet, and if it does, then without truncating it? 如果文件不存在则创建 - Create a file if it doesn't exist Android如果不存在python,如何创建一个新的json文件 - Android How to create a new json file if it doesn't exist python python 如果不存在则创建 json 文件,否则追加 - python create json file if it doesn't exist otherwise append python pyAutoGUI 给出一个文件不存在但它确实存在的错误 - python pyAutoGUI is giving an error that a file doesn't exist yet it does Python 会抛出一个文件不存在的错误 - Python throws an error that file doesn't exist when it clearly does 如何检查数组中某行是否存在,如果不存在则创建它,或者如果它在python中存在则修改它 - How to check for the existence of a row in an array, create it if it doesn't exist, or modify it if it does exist in python Python open() 在 w+ 模式下不创建文件 - Python open() doesn't create a file when in w+ mode
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM