Python, 'open' 和 'with open' 之间的区别

标签 python file

<分区>

我没有使用过 with 语句,但对它的用途有些熟悉。使用以下代码,#1 block 按预期工作,但是 #2 - 在这里纠正我,应该做与第一个相同的事情 - 抛出以下异常 FileExistsError: [Errno 17] File exists: 'mydir'

import os

if not(os.path.exists('mydir')):
    os.makedirs('mydir')

path = 'mydir'
filename = 'msg.txt'
filename2 = 'msg2.txt'

#1
with open(os.path.join(path, filename), 'w') as temp_file:
    temp_file.write("hello")

#2
temp_file = open(os.path.join(path, filename2), 'w')
temp_file.write("hello again")
temp_file.close()   

最佳答案

第 1 部分:open 之间的区别和 with open

基本上,使用 with只是确保您不会忘记 close()文件,使其更安全/防止内存问题。

第 2 部分:FileExistsError

这是一个操作系统错误,因此可能是特定于操作系统的。不过,假设您想覆盖(截断)之前的文件,您的语法是正确的。

这可能就是为什么问题是操作系统特定的,而大多数其他用户无法重现该问题的原因。

但是,如果它导致问题,您可以尝试使用 w+模式,它可能会解决问题。

A similar issue was documented here.

编辑:我刚刚注意到关于 teams 的评论流原来是路径。很高兴它得到修复!

关于Python, 'open' 和 'with open' 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34429519/

相关文章:

python 在给定索引的列表中查找项目

python - 获取 m 个值中 n 个错误回答的行

python - Python –没有错误但也没有返回数据

python - 将txt文件读入列表Python

java - 从相对路径读取 XML - java.io.FileNotFoundException :(The system cannot find the path specified)

python - 如何将文本文件制作成数组列表(数组中的数组)并删除空格/换行符

python - Python中的代码组织: Where is a good place to put obscure methods?

python - 如何根据不同列中的值将一列添加到 pandas 数据框?

c - 为什么“while(!feof(file))”总是错误的?

python - 使用 pynotify 读取新行