Skip to content Skip to sidebar Skip to footer

Python, Difference Between 'open' And 'with Open'

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

Solution 1:

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!

Solution 2:

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

ifnot(os.path.exists('teams')):
    os.makedirs('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'ifnot(os.path.exists(path)):
    os.makedirs(path)

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.

Post a Comment for "Python, Difference Between 'open' And 'with Open'"