Python Forum
Question on `print f.read()` behavior
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Question on `print f.read()` behavior
#1
Say I open a file using

lookingatfile = open([i]filename[/i])

when I then type

print lookingatfile.read()

the contents of the file are output.

However, if I open a file using

lookingatfile = open([i]filename[/i])

and then I type
x = lookingatfile.read()

nothing is output to the screen when I type print lookingatfile.read() and I only get text output to the screen when type print x

Why does print lookingatfile.read() print nothing, once I've assigned it to a variable in the script (eg, using x = lookingatfile.read())?
Reply
#2
You could have that succeed if right before that you use lookingatfile.seek(0). Basically, when you read from a file a "pointer" is advanced from position 0, and that position is saved. If you read the whole file, then you're at the end, and when it tries to read it again it finds there's nothing left. Usually we don't read from a file manually, we iterate over the lines in a file, and this behavior that you might find confusing is actually consistent with that use case as well as how files are often read manually (as in the C programming language).
Reply
#3
Ah - thanks. That explains it Thumbs Up
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Question: print issue python202209 3 956 Sep-18-2022, 11:51 AM
Last Post: jefsummers
Exclamation question about input, while loop, then print jamie_01 5 2,648 Sep-30-2021, 12:46 PM
Last Post: Underscore
  Why it does not print(file.read()) Rejaul84 1 2,330 Jul-01-2021, 10:37 PM
Last Post: bowlofred
  question about python3 print function jamie_01 5 2,624 May-25-2020, 09:58 AM
Last Post: pyzyx3qwerty
  Read serial BR=9600 . print me 2 lines? korenron 1 2,263 Dec-31-2019, 06:39 PM
Last Post: DeaD_EyE
  question on PRINT PEIXI 4 3,451 Oct-13-2018, 06:46 PM
Last Post: PEIXI
  Using for loops and indexing to read and string and print only select words Drone4four 3 3,877 Sep-13-2018, 02:51 PM
Last Post: buran
  read/print from file mcmxl22 8 7,192 Dec-29-2016, 07:54 AM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020