5. Reading Between the Lines


#1



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


I tried to do what in the instruction as in given below

Declare a new variable my_file and store the result of calling open() on the "text.txt" file in "r"ead-only mode.
On three separate lines, print out the result of calling my_file.readline(). See how it gets the next line each time?
Don't forget to close() your file when you're done with it!)

and my code for this above question is given below but i am getting and error

Oops, try again. Sorry, but I'm gonna need you to refresh the page! Don't worry your code is saved.

can anyone help me with this problem

thanks


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

print my_file.read()

my_file.close()


#2

Hi @shahidkhan0211,

This exercise buggy, and sometimes gives users trouble. The text.txt file might not exist.

Add this to the beginning of your code so that it creates the file and writes some lines to it, if it does not yet exist.

# Create the file
f = open("text.txt", "w+")
f.write("Hello World!" + "\n")
f.write("Hello World!!" + "\n")
f.write("Hello World!!!" + "\n")
f.close()

If the file does exist, it will replace its content.

After that, you can open and read it.


#3

i guess you misread the instructions. instead of using read() you have to put .readline()

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

it might ask you to save and refresh the page .


#4

You are correct; the instructions ask the user to do this ...

On three separate lines, print out the result of calling my_file.readline().


#5

I'm having similar issues:

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

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

my_file.close()

the error message reads: "IOError: [Errno 2] No such file or directory: 'text.txt'"

and the pop-up message asks me to refresh the page.

The text file also exists:

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

It may be a bug


#6

@daghaie,

Yes, the exercise is buggy, as many users have discovered. If you add this to the beginning of your code, does it help? ...

# Buggy exercise
# Create, write, and close the file.
f = open("text.txt", "w+")
f.write("Hello World!\n")
f.write("Hello World!!\n")
f.write("Hello World!!!\n")
f.close()

#7

Yep! Glad it wasn't on my end! Thanks for getting me through that portion!


#8

2 posts were split to a new topic: Reading Between the Lines


#9