I wanted to modify Exercise 16 in LP3THW to print the updated test.txt file. My first try, with just adding a line of code:
print(target.read())
returned an error:
“Traceback (most recent call last):
File “ex16.py”, line 37, in
print(target.read())
io.UnsupportedOperation: not readable”
I took this to mean that
target = open(filename, 'w')
only opens filename for writing, and not for reading, too.
So I decided to close the file, then reopen it as ‘new_target’ in read-mode. This removes the error message, but instead of printing out the file’s contents, it’s just printing a blank line.
#Exercise 16.
from sys import argv
script, filename = argv
print(f"We're going to erase {filename}.")
print("If you don't want that, hit CTRL-C (^C).")
print("If you do want that, hit RETURN.")
input("?")
print("Opening the file...")
target = open(filename, 'w')
print("Truncating the file. Goodbye!")
target.truncate
print("Now I'm going to ask you for three lines.")
line1 = input("line 1: ")
line2 = input("line 2: ")
line3 = input("line 3: ")
print("I'm going to write these to the file.")
target.write(f"""
{line1}
{line2}
{line3}
""")
target.close
print("Here are the contents of your file:")
new_target = open(filename)
#This is printing a blank line, instead of the user input.
print(new_target.read())
print("And finally, we close it.")
new_target.close
I have extracted the lines I made into a new script:
from sys import argv
script, filename = argv
print("Here are the contents of your file:")
new_target = open(filename)
#This is printing a blank line, instead of the user input.
print(new_target.read())
print("And finally, we close it.")
new_target.close
and this runs and prints out the file correctly.
Does this mean that the file isn’t updated when i close() it? How can I differentiate between a) the file hasn’t been updated yet with the user input and b) the file has been updated but print(new_target.read()) isn’t working?
I’m interested in why this isn’t working because it seems relevant to deepening my understanding of the mechanics in python of opening files and writing to them.