Error: No such file: 'text.txt'

<PLEASE USE THE FOLLOWING TEMPLATE TO HELP YOU CREATE A GREAT POST!>

<Below this line, add a link to the EXACT exercise that you are stuck at.>
https://www.codecademy.com/courses/python-intermediate-en-OGNHh/1/1?curriculum_id=4f89dab3d788890003000096
<In what way does your code behave incorrectly? Include ALL error messages.>
I have no idea what is going on. I wrote the my_file properly. Right? Or, is the tab that says “text.txt” not the name as seen there?

<What do you expect to happen instead?>
I expected it to accept.

```python

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

print my_file.readline(1)
print my_file.readline(2)
print my_file.readline(3)

my_file.close()

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

<do not remove the three backticks above>
1 Like

This is a bit of code contributed by @zeziba some time ago. There is a short work around for this, but it doesn’t teach as much as this does. Dig around for topics on this exercise. There are a few.

Above your working code,

try:
    my_file = open('text.txt', 'r')
    my_file.close()
    with open("text.txt", 'r') as file:
        file.seek(0)
        for line in file:
            print(line)
except:
    with open("text.txt", 'w+') as file:
        for i in range(3):
            file.write('{} {} \n'.format('New Line', i))
        file.seek(0)
        for line in file:
            print(line)

I received this error as well. From the error message I inferred that their was no “text.txt” file. So I did a quick google search on how to list directories. This confirmed my suspicion. From there I simply wrote the expected output to the file text.txt then closed the file. Then read from the file that I just created. Here is my code.

import os
for file in os.listdir("."):
    print(file)

my_file = open("text.txt", "w")
print my_file.write("I'm the first line of the file!\n")
print my_file.write("I'm the second line.\n")
print my_file.write("Third line here, boss.\n")
my_file.close()

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