LPthw Ex 16 (modified)

Hi I tried to modify the ending a little but couldn’t get it to work the way I wanted to. Any pointers would be helpful.

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.”)

prompt = ":> "

input(prompt)

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(line1)

target.write("\n")

target.write(line2)

target.write("\n")

target.write(line3)

target.write("\n")

print(“And finally, we print then close it.”)

with open(target, ‘r’) as fo:

print(fo.read())

Here is the error :

image

And if I changed the code to

with open('text.txt') as fo:

    fo_contents = fo.read()

    print(fo_contents)

There will be no error but no print out either

image

Somehow I got it to work this way >

image

End result >

PS C:\Users\Spuzzy\Documents\Python> python ex16.py text.txt
We’re going to erase text.txt.
If you don’t want that, hit CTRL-C (^C).
If you do want that, hit RETURN.
:>
Opening the file…
Truncating the file. Goodbye!
Now I’m going to ask you for three lines.
Line 1: 111
Line 2: 222
Line 3: 333
I’m going to write these to the file.
And finally, we print then close it.
111
222
333

I’m thinking I shouldn’t use open() with a target/object ? And it should be a file instead ?

I also added target.close() after the previous print.