Error: No such file: 'text.txt'


#1



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

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?


I expected it to accept.


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 <module>
IOError: [Errno 2] No such file or directory: 'text.txt'


#2

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)

#3

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