3. Writing, why doesn't this work?


#1


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

Here is my code:

my_list = [i**2 for i in range(1,11)]
my_file = open("output.txt", "r+")

for item in my_list:
    my_file.write("%s \n" % (item))
my_file.close()



An error message claims that the output does not "contain each element on its own line", but the output actually seems fine:

1
4
9
16
25
36
49
64
81
100

By changing line 5 to

my_file.write(str(item)+"\n")

it fixes the problem, but I would have thought

my_file.write("%s \n" % (item))

would amount to the same thing.


#2

@ryu_l,
The problem
you are using an extra space-character in your

my_file.write("%s \n" % (item))

Try to use

my_file.write("%s\n" % (item))

#3


what is wrong?


#4

@xianrui,
And if you =click= on the output.txt-tab
what do you see....!!!


3/9 Writing
#5

Thank you. That fixes the problem!


#6

i have the same code, and when i click the tab, the first 10 are fine, then its 3 lines of 100. i dont understand!!


#7

@kyle.francis
Please display the Full code you are using....


#8

i got it working! thank you though!


#9

my_list = [i**2 for i in range(1,11)]

my_file = open("output.txt", "r+")

Add your code below!

for item in my_list:
my_file.write("%s \n" % (item))

my_file.close()
str(42)

here's my code and my error is:

Oops, try again.
It looks like your file doesn't contain each element from my_list on its own line.

#10

@rajluckshmi
Why do you use

str(42)

And remove the extra space-character
from

my_file.write("%s \n" % (item))

into

my_file.write("%s\n" % (item))

#11

Thank you so much for rectifying


#12

I have that same issue right now, any help?

python 
my_list = [i**2 for i in range(1,11)]

my_file = open("output.txt", "r+")

for item in my_list: 
    my_file.write("%s\n" % (item))

my_file.close()

#14

Without that Python word up there your code works...


#15

@leonhard.wettengmx.n can't we also just use the following instead of using %s??

my_list = [i**2 for i in range(1,11)]

my_file = open("output.txt", "r+")

for i in my_list:
    my_file.write("i\n") # without using ("%s\n" %(item))
my_file.close()

#16

@orouge
Did you try using your

my_file.write("i\n") # without using ("%s\n" %(item))


#17

I did @leonhard.wettengmx.n even though with %s it makes more sense I just wanted to check whether it works without it. Thank you!


#18

@orouge ,

After you have tried this ...

my_file.write("i\n") # without using ("%s\n" %(item))

... be sure to check the resulting contents of the output.txt file. Does it contain what you expected?


#19

@appylpye

it gave an error


#20

@orouge ,

What was the error message?


#21

@appylpye
it gave me a pass but i remember the result was not right one.

also I sent you a couple more question in regards to ruby on rails. I was wondering if you had a chance to look at them? thanks in advance!