你如何在Python中将文件读入列表中?

这个问题在这里已经有了答案:

  • 在Python中,如何逐行读取文件到列表中? 35个答案

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

    这会给你一个你的文件中的值(字符串)列表,并删除换行符。

    另外,请在windows路径名称中注意反斜杠,因为这些也是字符串中的逃逸字符。 您可以使用正斜杠或双反斜杠。


    两种在python中将文件读入列表的方法(注意这些不是或者) -

  • 使用with - 来自python 2.5及以上版本
  • 使用列表解析
  • with

    这是打开和阅读文件的pythonic方式。

    #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.
    

    .strip()用于文件的每一行以删除n每行可能具有的换行符。 当with结束后,该文件将自动为您关闭。 即使在它内部引发异常,情况也是如此。

    2.使用列表理解

    这可能被认为是低效的,因为文件描述符可能不会立即关闭。 在一个打开数千个文件的函数中调用这个函数时,这可能是一个潜在的问题。

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

    请注意,文件关闭是依赖于实现的。 通常,未使用的变量是由python解释器收集的垃圾。 在cPython(python.org的常规解释器版本)中,它会立即发生,因为它的垃圾收集器通过引用计数工作。 在另一个解释器中,如Jython或Iron Python,可能会有延迟。


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

    看看这里。 readlines()返回一个包含每个元素一行的列表。 请注意,这些行在行尾包含n (换行符)。 你可以使用strip()方法去掉这个换行符。 即呼叫lines[index].strip()以获得没有换行符的字符串。

    正如joaquin指出的,不要忘记f.close()文件。

    将strint转换为整数很简单: int("12")

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

    上一篇: How do you read a file into a list in Python?

    下一篇: python copy files to a network location on Windows without mapping a drive