2

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) 
2
  • What did you expect the first version of your code to do? Surely calling readline again should let you print the fourth line from the file, rather than re-printing the first three lines as your working version does. Commented Aug 30, 2019 at 6:47
  • Sorry, you’re right my code is a little misleading, in the second version of the code I could have put only one of the variable but I just wanted to understand why I could still print any of the variable when the file has been closed, but I guess I had my answer which is that the variable was in memory and that’s where I’m printing from and not from the file; that’s why I was confused :-) Commented Aug 30, 2019 at 14:17

2 Answers 2

2

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot your answer is very appreciated my friend ,God bless!
1

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.

1 Comment

This does not fully answer the question. Further, the last line is a little misleading.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.