Bug in 3/9


#1

I've run this code snippet on my local machine and it works fine:

my_list = [i**2 for i in range(1,11)]
my_file = open("output.txt", "r+")
for x in my_list:
    my_file.write(str(x) + "\n")
my_file.close()

It's giving this weird output:

1
4
9
16
25
36
49
64
81
100
, 81, 100]

In fact, if I remove the + "\n" in the write() line, I get this:

14916253649648110064
81
100
, 81, 100]

so there is an extra 64, 81, 100

I'm not replicating this behavior on my local machine.


#2

Figured it out. I went through the archive and it appears I accidentally wrote a file with more lines. I switched

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

to

my_file = open("output.txt", "w")

to create a new file


#4

You have not a clear output.txt file.


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

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

for i in my_list:
    my_file.write(str(i))
    my_file.write("\n")

my_file.close()

#6

I generated basically the same code as you (without the duplication issue), but I'm throwing an error.

Here's what I wrote:

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

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

for items in my_list:
    my_file.write(str(items),"\n")

my_file.close()

This is the error I got... I'm going to use the solution below, but it was annoying trying to figure out why this syntax wouldn't work. In the example they give in 1/9, the function has 2 arguments! Definitely seems like an editing issue.

Traceback (most recent call last):
File "python", line 7, in
TypeError: function takes exactly 1 argument (2 given)


#7

the problem is with the write statement.

Note the difference between yours:

my_file.write(str(items), "\n")

and the correct version:

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

the comma here makes it that python takes the second part after the comma as a second argument. The correct version they also use in 1/9 in the excample, has only one argument that consist of a concatenated (by +) string.

Hope this helps.


#8

OH!!!! Totally missed the "+" in 1/9. It was an editing issue...mine! Haha

Thanks!