Python Forum
open a text file using list()
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
open a text file using list()
#1
I saw this today for opening a text file:

with open(file) as f:
    lines = list(f)
Never seen that before, I only know readlines(), which delivers the same thing, I think!?

Is it OK to do this? How can it work?
Reply
#2
f is iterable, and it yields lines, where the line ending is not stripped away.
list(f) consumes the iterator.


Example with a finite generator:
def generator():
    yield 1
    yield 2
    yield 3


# now we want everything from generator
values = list(generator())
Pedroski55 likes this post
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#3
In addition to Dead_EyE: as explicitly stated Python's documentation, the build-in list-class can take an iterable as the argument and return a list from the iterable.

The file object created by the open function is iterable, which is also shown in the Python tutorial. That list(f) works is even explicitly mentioned right there, next to the information that list(f) and f.readlines() do the same thing.

If you have some time to spare, maybe it's a good idea to take another dive into Python's tutorial.

Regards, noisefloor
DeaD_EyE and Pedroski55 like this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  If I open a file write or append, is the file loaded into RAM? Pedroski55 11 1,118 Jan-14-2026, 07:49 AM
Last Post: Pedroski55
Question [SOLVED] Open file, and insert space in string? Winfried 7 2,524 May-28-2025, 07:56 AM
Last Post: Winfried
  Get an FFMpeg pass to subprocess.PIPE to treat list as text file? haihal 2 2,461 Nov-21-2024, 11:48 PM
Last Post: haihal
  Trying to open depracated joblib file mckennamason 0 2,156 Sep-19-2024, 03:30 PM
Last Post: mckennamason
  Open/save file on Android frohr 0 2,187 Jan-24-2024, 06:28 PM
Last Post: frohr
  file open "file not found error" shanoger 8 17,397 Dec-14-2023, 08:03 AM
Last Post: shanoger
  How can i combine these two functions so i only open the file once? cubangt 4 2,703 Aug-14-2023, 05:04 PM
Last Post: snippsat
  Start print a text after open an async task via button Nietzsche 0 1,604 May-15-2023, 06:52 AM
Last Post: Nietzsche
  I cannot able open a file in python ? ted 5 15,868 Feb-11-2023, 02:38 AM
Last Post: ted
  testing an open file Skaperen 7 3,674 Dec-20-2022, 02:19 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

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