file python readlines string

How to read a file line-by-line into a list?


How do I read every line of a file in Python and store each line as an element in a list?

I want to read the file line by line and append each line to the end of the list.


    See Input and Ouput:

    with open('filename') as f:
        lines = f.readlines()

    or with stripping the newline character:

    with open('filename') as f:
        lines = [line.rstrip() for line in f]


    • 78

      Better, use, which does remove newlines

      – Mark

      Aug 28, 2015 at 7:48

    • 1

      Is the second version, with for line in open(filename) safe? That is, will the file be automatically closed?

      – becko

      Feb 10, 2016 at 15:30

    • 2

      Best to read the file one line at a time rather than reading the whole file into memory all at once. Doing so doesn’t scale well with large input files. See below answer by robert.

      – Brad Hein

      Mar 3, 2016 at 19:45

    • 2

      lines = [x.rstrip('\n') for x in open('data\hsf.txt','r')] If I write this way, how can I close the file after reading?

      May 11, 2018 at 14:16

    • 3

      Yes, to the point others are making here, while it’s not “best practice” to use open without the context manager (or some other guaranteed way to close it), this is not really one of those cases – when the object has no more references to it it will be garbage collected and the file closed, which should happen immediately on error or not, when the list comprehension is done processing.

      May 16, 2018 at 21:25


    This is more explicit than necessary, but does what you want.

    with open("file.txt") as file_in:
        lines = []
        for line in file_in:


    • 40

      I prefer this answer since it doesn’t require to load the whole file into memory (in this case it is still appended to array though, but there might be other circumstances). Certainly for big files this approach might mitigate problems.

      – JohannesB

      Sep 19, 2018 at 12:44

    • 4

      Appending to an array is slow. I cannot think of a use case where this is the best solution.

      Oct 4, 2018 at 12:48

    • 11

      Note: This solution does not strip newlines.

      – AMC

      Jan 9, 2020 at 18:31

    • 10

      This solution does load the whole file to memory. I don’t know why people think it does not.

      May 4, 2020 at 20:33

    • 2

      @andrebrait It loads the whole file into lines[] by choice, but can just load line by line.

      Jun 10, 2020 at 23:15