Section 8 (Try it yourself)


#1



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


Why is the following code not printing "Foobar"?


with open('text.txt', 'r+') as my_file:
    my_file.write("Foobar")
    print my_file.read()


#2

The above statement does not create the file. Try using the 'w' mode to create the file, then open it with the 'r+' mode.

with open('text.txt', 'w') as my_file:
    my_file.write("Foobar")
with open('text.txt', 'r+') as my_file:
    my_file.write("FooBar")
    print my_file.read()

Note that the second write statement overwrote the first.


#3

But the file already exists in this exercise. Why do you need to recreate it?


#4

I think I may have refreshed the page and the file was lost. Too many hours ago to remember for sure. All I know is the above worked and passed.


#5

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