Skip to main content
 首页 » 编程设计

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

2025年05月04日28exmyth

<分区>

我没有使用过 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()