Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, difference between 'open' and 'with open' [duplicate]

Tags:

python

file

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()   
like image 917
francium Avatar asked Mar 02 '26 02:03

francium


1 Answers

Part 1: The Difference Between open and with open

Basically, using with just ensures that you don't forget to close() the file, making it safer/preventing memory issues.

Part 2: The FileExistsError

This is an OS error and, therefore, may be OS specific. Your syntax is correct though, assuming that you want to overwrite (truncate) the previous file.

This is probably why the problem is OS-specific and most other users are unable to duplicate the issue.

However, if it's causing issues, you could try using w+ mode and it may fix the issue.

A similar issue was documented here.

EDIT: I just noticed the comment stream about teams originally being the path. Glad it got fixed!

like image 56
Leejay Schmidt Avatar answered Mar 03 '26 15:03

Leejay Schmidt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!