Weird Result on Writing


#1

Browser says file doesn't contain each element on the list on its own line, although the result in the output tab seems precise.

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

#2

So I passed the exercise by just deleting the first line of code. no result was shown in the browser's new tab
the interpre3ter raised an syntax error and I passed. Can someone explain?


#3

At first why your code didn't work is because you were trying to open the same file twice which of course cannot be done. The reason you passed with an error, that means that the SCT did not account for the error that occurred or control flow of the code you had written.


#4

Many thanks for the rapid response. But, as I said the output file showed the expected result and the browser said it didn't.


#5

The problem is on thsi line you are supposed to add str(i) + \n not display it as a string,

to,

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

Also this should just be, 'w' and not 'r+',


#6

Thanks again, bandit.


#7