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