F-string returns file object name

Question:

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!

Asked By: RTGho

||

Answers:

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

print(f'Your {filename} file is now open for editing ')
Answered By: Kirill
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.