File I/O - Reading


#1



https://www.codecademy.com/en/courses/python-intermediate-en-OGNHh/0/4?curriculum_id=4f89dab3d788890003000096#


What happens if I do not close the file?


my_file=open("output.txt","r")
print my_file.read()
my_file.close()


#2

the file will stay in memory.


#3

For the same code above, when I came back to this exercise from the next exercise, I got the following error.

Traceback (most recent call last):
File "python", line 1, in
IOError: [Errno 2] No such file or directory: 'output.txt'

Why does the code work once but not the second time?


#4

because there are problems with the exercise, its a known bug


#5

Thanks for the clarification. The following exercise where the code is as below, did not work even the first time. The second time it is showing a different error and asking me to refresh the page. How do I complete this exercise?
Link:
https://www.codecademy.com/en/courses/python-intermediate-en-OGNHh/1/1?curriculum_id=4f89dab3d788890003000096#

Error:
Traceback (most recent call last):
File "python", line 1, in
IOError: [Errno 2] No such file or directory: 'text.txt'

my_file=open("text.txt","r")
print my_file.readline()
print my_file.readline()
print my_file.readline()
my_file.close()

#6

open the file in writing more, write 3 lines to file, close file.


#7

I have nowhere mentioned output.txt in my code. But I am getting this error.

Oops, try again. Make sure you're trying to open text.txt, not output.txt!

In the console :
Traceback (most recent call last):
File "python", line 3, in
IOError: File not open for reading


#8

i can't see what you did if you don't post your code


#9

Sorry stetim94. Here is my code:

my_file=open("text.txt","w")

print my_file.readline()
print my_file.readline()
print my_file.readline()
my_file.close()

#10

the file is named output.txt?

also, when opening in write mode, you need to write to file, then close it, open it again for reading and read from file


#11

The name of the file is text.txt as you can see from the screenshot


#12

Solved by changing "w" to "r".

I finished the Python course completely. Thanks a lot @Stetim94.


#13

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.