Cedric
Cedric

Reputation: 21

Clarification about the close method in Python file handling

I apologize if this will sound like a basic question but I'm seeking clarification on the close method in python, I am not understanding why after closing the file I can still print the variable that points to the file

if I run the below:

poem1 = open('poem1.txt', 'r')

poem_line1 = poem1.readline()
poem_line2 = poem1.readline()
poem_line3 = poem1.readline()

print(poem_line1 + poem_line2 + poem_line3)

poem1.close()

print(poem1.readline())

I will get the correct message:

"ValueError: I/O operation on closed file."

but if I replace the last line directly printing the file, there is no error:


poem_line1 = poem1.readline()
poem_line2 = poem1.readline()
poem_line3 = poem1.readline()

print(poem_line1 + poem_line2 + poem_line3)

poem1.close()

print (poem_line1 + poem_line2 + poem_line3)

Upvotes: 2

Views: 58

Answers (2)

Engineering Projects
Engineering Projects

Reputation: 80

The method close() closes the opened file. A closed file cannot be read or written any more.

Any operation, which requires that the file be opened will raise a ValueError after the file has been closed.Python automatically closes a file when the reference object of a file is reassigned to another file. It is a good practice to use the close() method to close a file. Once you close the file you can not print those file because they are not open your compiler will not find anything.

Upvotes: 1

micharaze
micharaze

Reputation: 976

The line poem_line1 = poem1.readline() reads a line from the file and put it as a string in a variable. So after that the line is copied on the memory. This is the reason why you can still use this variable after closing the file.

So with the line print (poem_line1 + poem_line2 + poem_line3) you are not printing from the file, you are printing the string from the variables (from the memory).

Upvotes: 2

Related Questions