Python,“打开"和“具有打开"之间的区别 [英] Python, difference between 'open' and 'with open'

查看:56
本文介绍了Python,“打开"和“具有打开"之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有使用 with 语句,但是对它的用途有些熟悉.使用以下代码,#1 块可以按预期工作,但是#2 -在这里纠正我的意思,应该和第一个相同-抛出以下异常 FileExistsError:[Errno 17]文件存在:"mydir" .

I have not used the with statement, but am somewhat familiar with its purpose. With the follow code, the #1 block works as expected, but #2 -- which, correct me here, should do the same thing as the first one -- throws the following exception 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()   

推荐答案

此错误是由发布的脚本的先前版本引起的.看起来像这样:

This error was caused by a previous version of the posted script. It looked like this:

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

这将测试目录 teams 的存在,但尝试创建新目录 mydir .

This tests for the existence of the directory teams but tries to create a new directory mydir.

建议的解决方案:对所有内容都使用变量名,不要对路径使用硬连线字符串:

Suggested solution: use variable names for everything, don't hardwire strings for paths:

path = 'mydir'

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

是的,#1 #2 基本上是相同的.但是 with 语句也会在写入过程中发生异常的情况下关闭文件.

And yes, both #1 and #2 do essentially the same. But the with statement also closes the file in case of an exception during writing.

这篇关于Python,“打开"和“具有打开"之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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