How do you read a file into a list in Python?

This question already has an answer here:

  • In Python, how do I read a file line-by-line into a list? 35 answers

  • with open('C:/path/numbers.txt') as f:
        lines = f.read().splitlines()
    

    this will give you a list of values (strings) you had in your file, with newlines stripped.

    also, watch your backslashes in windows path names, as those are also escape chars in strings. You can use forward slashes or double backslashes instead.


    Two ways to read file into list in python (note these are not either or) -

  • use of with - supported from python 2.5 and above
  • use of list comprehensions
  • 1. use of with

    This is the pythonic way of opening and reading files.

    #Sample 1 - elucidating each step but not memory efficient
    lines = []
    with open("C:nameMyDocumentsnumbers") as file:
        for line in file: 
            line = line.strip() #or some other preprocessing
            lines.append(line) #storing everything in memory!
    
    #Sample 2 - a more pythonic and idiomatic way but still not memory efficient
    with open("C:nameMyDocumentsnumbers") as file:
        lines = [line.strip() for line in file]
    
    #Sample 3 - a more pythonic way with efficient memory usage. Proper usage of with and file iterators. 
    with open("C:nameMyDocumentsnumbers") as file:
        for line in file:
            line = line.strip() #preprocess line
            doSomethingWithThisLine(line) #take action on line instead of storing in a list. more memory efficient at the cost of execution speed.
    

    the .strip() is used for each line of the file to remove n newline character that each line might have. When the with ends, the file will be closed automatically for you. This is true even if an exception is raised inside of it.

    2. use of list comprehension

    This could be considered inefficient as the file descriptor might not be closed immediately. Could be a potential issue when this is called inside a function opening thousands of files.

    data = [line.strip() for line in open("C:/name/MyDocuments/numbers", 'r')]
    

    Note that file closing is implementation dependent. Normally unused variables are garbage collected by python interpreter. In cPython (the regular interpreter version from python.org), it will happen immediately, since its garbage collector works by reference counting. In another interpreter, like Jython or Iron Python, there may be a delay.


    f = open("file.txt")
    lines = f.readlines()
    

    Look over here. readlines() returns a list containing one line per element. Note that these lines contain the n (newline-character) at the end of the line. You can strip off this newline-character by using the strip() -method. Ie call lines[index].strip() in order to get the string without the newline character.

    As joaquin noted, do not forget to f.close() the file.

    Converting strint to integers is easy: int("12") .

    链接地址: http://www.djcxy.com/p/42340.html

    上一篇: 在Python中逐行读取文件到数组的元素中

    下一篇: 你如何在Python中将文件读入列表中?