Why isn’t the lesson accepting what I write to the file?

Question

Why isn’t the lesson accepting what I write to the file?

Answer

Be sure not to add any additional spaces or punctuation or unnecessary text to the output file since Codecademy checks for exactly what is asked for. A common error is using string formatting and putting a space between the current for loop variable being written and the newline character, \n.
To fix this, simply remove any spacing you wrote and just write() the current number and the newline character directly afterward.

2 Likes

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

my_file = open(“output.txt”, “w”)

Add your code below!

for i in my_list:
print i
my_file.write(“output.txt”"\n")

my_file.close()

It prints out each number on its own line but isn’t accpeted for some reason. Where abouts am I going wrong?

1 Like

Add the “+” operator in my_file.write like:
my_file.write(“output.txt” + “\n”)

1 Like

When I use that code, it works perfect, but is not accepted by the lesson. When I change my code to match the solution’s recommended code, my console registers an error and the lesson doesn’t accept it either. Is there a bug?

This should work (my code):

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

my_file = open(“output.txt”, “r”)
print my_file.read()
my_file.close()

1 Like

this works:

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

my_file = open(“output.txt”, “w”)

Add your code below!

for i in my_list:

my_file.write(str(i) + “\n”)

my_file.close()

My code prints the square of numbers 1 through 10 to the console but should I see something on the output.txt tab?

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

my_file = open(“output.txt”, “w”)

Add your code below!

for i in my_list:
print i
my_file.write(“output.txt” + “\n”)
my_file.close()

Thanks

If this is a tab open in the codecademy learning environment then it won’t be updated automatically when the file is altered in the background. Try closing and reopening that tab once you have run your script to view any changes made.

Thanks @tgrtim,
I advanced onto the next topic in the section and then pressed the back button and the output.txt tab was populated. Just wanted to make sure that I was correctly writing to the output file even though I could see that the squared results were correct by using the print command.

1 Like

Yes, I believe it’s a bug. I know because, after checking the solution, I had typed exactly what was written there and it still would not accept it. However, when I clicked “Replace with Solution” it automatically gave me the green light.