Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Reading a text file
#4
Just as a joke, but you can still learn about this.
Don't use this code.

with open(file_name) as fd:
    lineiterator = iter(fd)
    for line in lineiterator:
        print(line.strip())
        with contextlib.suppress(StopIteration):
            next(lineiterator)
fd is the file object.

The function iter(fd) makes an iterator from the file object.
This works only, when the file has been opened in text mode. Calling iter on a file object,
does the same what the for-loop does. The call next(lineiterator) jumps to the next line.
As you can see, there is no use of the returned data of next(lineiterator).
contextlib.suppress is just a context manager to suppress errors. In this case
StopIteration is suppressed. If this Exception StopIteration happend,
the end of file has been reached. The for-loop does get this Exception also and stops silently.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
Reading a text file - by fivestar - Oct-11-2017, 11:49 PM
RE: Reading a text file - by Larz60+ - Oct-12-2017, 12:33 AM
RE: Reading a text file - by wavic - Oct-12-2017, 11:26 AM
RE: Reading a text file - by DeaD_EyE - Oct-12-2017, 12:13 PM
RE: Reading a text file - by gruntfutuk - Oct-12-2017, 04:39 PM
RE: Reading a text file - by DeaD_EyE - Oct-12-2017, 06:55 PM
RE: Reading a text file - by snippsat - Oct-12-2017, 08:38 PM
RE: Reading a text file - by gruntfutuk - Oct-13-2017, 07:25 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Excel File reading vanjoe198 1 2,047 Mar-31-2021, 11:53 AM
Last Post: snippsat
  Reading a text until matched string and print it as a single line cananb 1 2,042 Nov-29-2020, 01:38 PM
Last Post: DPaul
  reading from a file looseCannon101 14 4,972 Jul-18-2020, 11:29 AM
Last Post: GOTO10
  Convert text from an image to a text file Evil_Patrick 5 4,305 Jul-30-2019, 07:57 PM
Last Post: DeaD_EyE
  Weird problem with reading from file and performing calculations pineapple999 1 3,018 Jul-25-2019, 01:30 AM
Last Post: ichabod801
  Handling IO Error / Reading from file Expel 10 4,894 Jul-18-2019, 01:21 PM
Last Post: snippsat
  Reading an Unconventional CSV file OzSbk 2 3,896 May-17-2019, 12:15 PM
Last Post: MvGulik
  reading text file and writing to an output file precedded by line numbers kannan 7 10,461 Dec-11-2018, 02:19 PM
Last Post: ichabod801
  Reading of structured .mat (matlab) file sumit 2 3,428 May-24-2018, 12:12 PM
Last Post: sumit
  File Reading toxicxarrow 9 5,193 May-07-2018, 04:12 PM
Last Post: toxicxarrow

Forum Jump:

User Panel Messages

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