如何在Python中读取文件的每一行,并将每一行存储为列表中的元素?

我想逐行读取文件,并将每一行附加到列表的末尾。


当前回答

命令行版本

#!/bin/python3
import os
import sys
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
filename = dname + sys.argv[1]
arr = open(filename).read().split("\n") 
print(arr)

运行方式:

python3 somefile.py input_file_name.txt

其他回答

这将从文件中生成一个“数组”。

lines = tuple(open(filename, 'r'))

open返回一个可以迭代的文件。当您遍历一个文件时,您会从该文件中获取行。tuple可以使用迭代器,并从您给它的迭代器中为您实例化一个tuple实例。

根据Python的文件对象方法,将文本文件转换为列表的最简单方法是:

with open('file.txt') as f:
    my_list = list(f)
    # my_list = [x.rstrip() for x in f] # remove line breaks

演示


如果只需要遍历文本文件行,可以使用:

with open('file.txt') as f:
    for line in f:
       ...

旧答案:

使用with和readline():

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

如果您不关心关闭文件,这一行程序将起作用:

lines = open('file.txt').readlines()

传统方式:

f = open('file.txt') # Open file on read mode
lines = f.read().splitlines() # List with stripped line-breaks
f.close() # Close file

如果文档中也有空行,我希望读取内容并将其通过过滤器以防止空字符串元素

with open(myFile, "r") as f:
    excludeFileContent = list(filter(None, f.read().splitlines()))

这比必要的更明确,但可以做到你想要的。

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

命令行版本

#!/bin/python3
import os
import sys
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
filename = dname + sys.argv[1]
arr = open(filename).read().split("\n") 
print(arr)

运行方式:

python3 somefile.py input_file_name.txt