Jumpman
Jumpman

Reputation: 439

Reading file on top of the previous one

I was wondering if it is perfectly safe to read one file onto another(before closing the buffer). Explanation for such a thing I would give is that the function open closes the buffer by itself automatically when using the same object.

Example code:

fr = open("asd.txt", "r")
text = fr.read()
fr.close

fr = open("asd2.txt", "r")
text = fr.read()
fr.close
...

Is this the same thing?

fr = open("asd.txt", "r")
text = fr.read()

fr = open("asd2.txt", "r")
text = fr.read()

fr.close

Upvotes: 1

Views: 45

Answers (2)

ForceBru
ForceBru

Reputation: 44838

You can do text=open("test.txt").read(), process the data and then open other files in the same manner. They will be closed as soon as the data is read.

A more pythonic way to work with files is to do this:

with open("test.txt") as your_file:
    text=your_file.read()

Note: when you want to close a file manually, you have to call the close function like this: your_file.close()

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121914

Yes, the second line is the same because neither snippet properly closes files.

You would have to call the fr.close() method to close the file object, without the () part the method is only referenced, not executed. So in both examples the 'asd.txt' file object is still open when the second open() call is executed.

In CPython (the default Python implementation downloadable from Python.org) file objects are automatically closed when no longer referenced, so as soon as the second open() call returns and is assigned, the first open file is closed as the reference to the object is removed.

However, you should really use the file object as a context manager instead, using the with statement:

with open("asd.txt", "r") as fr:
    text = fr.read()

with open("asd2.txt", "r") as fr:
    text = fr.read()

and more likely, use different variables names for text as one now replaces the other. File objects in a with statement are automatically closed when the block ends or an exception occurs in that block.

Upvotes: 4

Related Questions