-1

Trying to understand the output of the following code:


  1 #!/usr/bin/python3
  2
  3 from os.path import exists
  4
  5 filename = input("What file do you want to erase?: ")
  6
  7 check = exists(filename)
  8
  9 if check == True:
 10     target = open(filename, "r+")
 11     print(f'Your {target} file is now open for editing ')
 12     input("RETURN to ERASE.  CTRL + C to abort. " )
 13     target.truncate()
 14     print (f"Your {filename} file is now empty. ")
 15     target.write("#!/usr/bin/python3 ")
 16     target.close()
 17 elif check == False:
 18     print(f'That file  does not exist.  Come back later and try again ')
 19
 20
 21 another_file = input("Give me another file to erase:  ")
 22
 23 target = open(another_file, "r+")
 24
 25 print(f"This is the name {another_file} of the file you opened. ")
 26

OUTPUT

The code on line 11 outputs the following:

Your <_io.TextIOWrapper name='file1.txt' mode='r+' encoding='UTF-8'> file is now open for editing

All other f-string instances output the actual filename.

"Your file1.txt file is now empty....etc"

Trying to understand why that is. If anyone has any insights, I'd greatly appreciate it.

Thx!

2
  • 1
    target is the file handle not the filename Commented Aug 11, 2022 at 20:53
  • Change {target} to {filename} like on line 15. Commented Aug 11, 2022 at 20:55

1 Answer 1

0

Because you use "targer", "target" is file object. Use "filename"

print(f'Your {filename} file is now open for editing ')
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.