5/9 Reading between the lines: ERROR

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

Gives me the following error message:
Traceback (most recent call last):
File “python”, line 1, in
IOError: [Errno 2] No such file or directory: ‘text.txt’

The error is in line 1 which is defined as per the instructions… I expect no error in the code… can someone please explain why the error pops up?

Thanks in advance!

```python

my_file = open(“text.txt”, “r”)

for i in range(1,3):
print my_file.readline()

my_file.close()

<do not remove the three backticks above>
5 Likes

Don’t use a for loop that is why they say on three seperate lines So you would write it like this

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

done, error persists… infact i tried that before posting here…:confused:

2 Likes

Write something in the text.txt window

31 Likes

It should work after doing that :slight_smile:

8 Likes

I’m the first line of the file!
I’m the second line.
Third line here, boss.

these lines are already there

1 Like

Change the text. And then run the code but it has to be three lines of text like this,

  1. Hi
  2. Hey
  3. Woohoo
30 Likes

It worked now!!! :laughing::grin::sunglasses:

Thats a weird error!!!

3 Likes

You’re welcome! :grin:

1 Like

This worked for me too. Thanks bandit. Definitely a weird error.

2 Likes

I tried this, and I still get the below error.

Traceback (most recent call last):
File “python”, line 1, in
IOError: [Errno 2] No such file or directory: ‘text.txt’

Nevermind. I fixed it by changing “text.txt” to ‘text.txt’. Weird.

6 Likes

Just changing the text.txt file fixes everything. Weird bug in their course

That worked for me, thanks!

All I did was insert one word into the first line. I didn’t even delete the pre-populated text.

1 Like

Haha super cool. :grin:

1 Like

Thanks, bandit! That helped me out, too.

1 Like

You’re welcome :grin:

1 Like

Writing something in the text.txt tab worked for me when nothing else did. Thank you.

1 Like

Just for future reference instead of looping with a traditional count controlled loop you can loop through the file like you would a string or an array like this:

my_file =  open( "text.txt", "r" )
for line in my_file:
    print( line )
my_file.close()

This way when you don’t know how many lines are in the file you can still iterate through them all.

2 Likes

Bandit, it says On three separate lines, print out the result of calling my_file.readline(). which is referring to the result that will be printed in the console, not your code. It’s more efficient to use a loop here.