ChatGPT解决这个技术问题 Extra ChatGPT

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

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

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

最重要的是,我只需要一个解决问题的方法。我对其他的东西很好奇,但我需要的只是一个很好的方法来做开头部分。

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

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

正如 S.Mark 提到的,这应该“正常工作”。封闭目录是否可写?
muksie 在下面的回答有效(并且 baloo 也是如此),但为了完整起见,封闭的 dir 可由用户和组写入,而不是其他(我在 linux 系统上...所以权限 775 换句话说),以及确切的错误是 IOError:没有这样的文件或目录。谢谢你们的帮助。
确保 file 的所有前导文件夹都存在。

I
Igor Chubin

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

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

w 截断现有文件。 docs:模式 'r+''w+''a+' 打开文件进行更新(注意 'w+' 会截断文件)。
这成功了。谢谢你。我现在因为不阅读规范而觉得自己像个白痴。我不认为'rw'在那里甚至是可以接受的。我一定是在想别的东西。
请注意,如果文件不存在,a+ 会创建一个文件,并且至关重要的是,它会一直查找该文件。因此,如果您在以这种方式打开后立即阅读,您将一无所获。你需要先回到起点:f.seek(0)
这不是解决方案。 问题是目录。要么脚本缺乏在该目录中创建文件的权限,要么该目录根本不存在。 open('myfile.dat', 'w') 就足够了。
C
Community

以下方法的优点是文件在块的末尾正确关闭,即使在途中引发异常也是如此。它相当于 try-finally,但要短得多。

with open("file.dat","a+") as f:
    f.write(...)
    ...

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

seek() method 设置文件的当前位置。

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

只允许使用“rwab+”字符;必须有“rwa”之一 - 请参阅 Stack Overflow 问题 Python 文件模式详细信息。


我尝试使用 open(filename, 'a+') as myfile: 并得到 IOError: [Errno 2] No such file or directory: - 为什么它不创建文件?
@Loretta 您检查过 filename 的值吗?
是的,我做到了。它是一个 unicode 字符串。我还尝试使用 open('{}.txt'.format(filename), 'a+') 作为 myfile:
我没有使用路径。我尝试了 open('test.txt', 'a+') 它在 os.stat(myfile).st_size == 0 的行中出现以下异常 'TypeError: coercing to Unicode: need string or buffer, file found':
您需要正确定义编码才能使其正常工作。 stackoverflow.com/q/728891/3701431
b
bad_coder
'''
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
'''

例子:

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

[仅供参考,我使用的是 Python 3.6.2 版]


模式“w+”的缺点是截断文件,如果它已经存在的话。在许多情况下,这可能不是人们想要的。
l
lollercoaster

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

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

在打开文件之前测试它是不好的,因为它可能导致竞争条件(文件在打开之前被删除)。竞争条件有时可用于利用系统中的漏洞。 “a+”模式是打开文件的最佳方式:它创建一个新文件,并附加到现有文件。不要忘记将其包装在 try/except 中。
计算模式 write 或 append 没有兴趣。如果文件不存在,附加模式会创建它。
b
baloo

将“rw”更改为“w+”

或使用 'a+' 追加(不删除现有内容)


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

r+ 表示读/写


更糟糕的是,这段代码容易出现竞争条件。因此,在检查文件是否存在后,进程可能会被中断,另一个进程可以创建这个文件。
您还需要“w+”标志,这样两个文件都将处于读写模式。
G
Granitosaurus

从 python 3.4 开始,您应该使用 pathlib 来“触摸”文件。
这是一个比本线程中建议的解决方案更优雅的解决方案。

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)

与目录相同:

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

touch 在使用时会更新上次修改时间。
@DavidParks 好点,刚刚测试过,在 ext4 文件系统和 python3.7.2 上确实如此。我不认为这是预期或期望的行为,也许这是 python 的错误?
在 linux 的命令行中使用 touch 时也是如此,所以我认为这是预期的行为。
这引入了竞争条件。
@Tordek 怎么样?我不认为那是真的。
C
Chien-Wei Huang

我的答案:

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

h
hostingutilities.com

利用:

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

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


S
SilentGhost

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

在 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

在 python-2.6 中,它引发了 IOError


C
Chenglong Ma

对于 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(...)

所以,问题是 with open 在目标目录存在之前无法创建文件。我们需要创建它,然后在这种情况下 w 模式就足够了。


小心这个!如果文件存在,它将截断内容。
嗨@NONONONONO,是的,这就是 w 模式的作用。如果要保留现有内容,可以使用 a 追加模式。请参阅open() doc
N
Neuron

你想对文件做什么?只写它还是读写?

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

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


在打开之前测试存在可能会引入竞争条件。在这种情况下可能没什么大不了的,但要记住一些事情。
“如果您需要从文件中读取,则该文件必须在您打开之前存在。”谢谢你拯救了我的理智。
N
Neuron

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


G
Gustavo6046

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


D
Danilo Souza Morães

如果您想打开它进行读写,我假设您不想在打开它时截断它,并且希望能够在打开文件后立即读取文件。所以这是我正在使用的解决方案:

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

S
Stephen Ngethe

因此,您想将数据写入文件,但前提是它尚不存在?

这个问题很容易通过使用鲜为人知的 x 模式来 open() 而不是通常的 w 模式来解决。例如:

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

如果文件是二进制模式,请使用模式 xb 而不是 xt。


G
Ganesh Jat
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)