3. Writing


#1



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("output.txt")
    my_file.write("\n")
my_file.close()

Though I am told that I have succeeded, I receive the following error message:
Traceback (most recent call last):
File "python", line 3, in
IOError: [Errno 2] No such file or directory: 'output.txt'


#2

open the file in write mode (w), not append mode (r+)


#3

In the previous exercise it tells us to open it using the "r+" mode to "read and write" rather than using "w". When would you use each respectively?


#4

well, if the file not exist yet and you need to write to the file or you want to overwrite the current content, use w

if the file exist yet, and you want to append to the file, use r+, its in the information of the exercise


#5

Thanks, I probably read over it and didn't really register it.


#6

hey you might want to have a relook at your code
you are iterating right but are printing 'output.txt' for each item

my_file.write("Data to be written")

this is the correct way to enter the data
that means try replacing output.txt with the data that you want to be written in the output.txt


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.