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

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


当前回答

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

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

其他回答

这里还有一个选项,对文件使用列表理解;

lines = [line.rstrip() for line in open('file.txt')]

这应该是更有效的方法,因为大部分工作都是在Python解释器内完成的。

这段代码将把整个文件读入内存,并删除每行末尾的所有空白字符(换行符和空格):

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

如果您正在处理一个大文件,那么您应该逐行读取并处理它:

with open(filename) as file:
    for line in file:
        print(line.rstrip())

在Python 3.8及以上版本中,可以使用while循环和walrus运算符,如下所示:

with open(filename) as file:
    while (line := file.readline().rstrip()):
        print(line)

根据您计划对文件执行的操作以及文件的编码方式,您可能还需要手动设置访问模式和字符编码:

with open(filename, 'r', encoding='UTF-8') as file:
    while (line := file.readline().rstrip()):
        print(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

使用此项:

import pandas as pd
data = pd.read_csv(filename) # You can also add parameters such as header, sep, etc.
array = data.values

data是一种数据帧类型,使用值获取ndarray。您还可以使用array.tolist()获取列表。

具有文本文件内容:

line 1
line 2
line 3

我们可以在上面txt的同一目录中使用此Python脚本

>>> with open("myfile.txt", encoding="utf-8") as file:
...     x = [l.rstrip("\n") for l in file]
>>> x
['line 1','line 2','line 3']

使用追加:

x = []
with open("myfile.txt") as file:
    for l in file:
        x.append(l.strip())

Or:

>>> x = open("myfile.txt").read().splitlines()
>>> x
['line 1', 'line 2', 'line 3']

Or:

>>> x = open("myfile.txt").readlines()
>>> x
['linea 1\n', 'line 2\n', 'line 3\n']

Or:

def print_output(lines_in_textfile):
    print("lines_in_textfile =", lines_in_textfile)

y = [x.rstrip() for x in open("001.txt")]
print_output(y)

with open('001.txt', 'r', encoding='utf-8') as file:
    file = file.read().splitlines()
    print_output(file)

with open('001.txt', 'r', encoding='utf-8') as file:
    file = [x.rstrip("\n") for x in file]
    print_output(file)

输出:

lines_in_textfile = ['line 1', 'line 2', 'line 3']
lines_in_textfile = ['line 1', 'line 2', 'line 3']
lines_in_textfile = ['line 1', 'line 2', 'line 3']