Reading lines in a file


Hello everyone,

I am back again. I am just a step away from completing my course in Python but I am stuck again. The problem statement can be reached through the following link:-

In short, the question requires me to read a file named 'text.txt' line by line. I have written the following code: -

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

Please help me find the mistake in the code. Thank you in advance for your time and help.


same problem here. wrote the same code.



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

you are trying to open an existing read modus.....
If you use following code
you will see which files are available....

import os
print "==show us the existing files =="
files = [f for f in os.listdir('.') if os.path.isfile(f)]
for f in files:
    print str(f)


With following code
you will do a test of the existence of text.txt file
and if the file text.txt is not found
you will create the text.txt file

import os
print "== if the file doesn't exist, create one =="
if os.path.exists('text.txt'):
    print "File exists"
    print "Creating the text.txt-file"
    my_file = open("text.txt", 'w')
    my_file.write("I'm the first line of the file!" +"\n")
    my_file.write("I'm the second line."+"\n")
    my_file.write("Third line here, boss."+"\n")

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

== discussions / opinions ==


thanks. the code worked for me.


Thank you @leonhard.wettengmx.n for helping me!


Thanks leonhard.wettengmx.n for solving this bug!
It was bothering me to have Python course stuck on 99%


Thanks @leonhard.wettengmx.n . the code is perfect :wink:


Thanks! That was perfect.


Gracias por solucionar este detalle del curso Leonard!!!

Thanks for solving this bug Leonard!!!


Thanks for helping me with this bug! They should really fix this...


Another way to deal with this is you create the "text.txt" file by yourself. I have the same problem, and I use the following code to solve this bug.

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


So this problem has been broken for at least months.... and it still is....

I really want to have faith in humanity but its really hard with crap like this. Free or not it was reported months ago. You created something to teach green horns how to code. So either do that or don't. Not here to argue about the value of a problem or what it teaches. All you got to do is make it work.