如何在Python中读取文件的每一行,并将每一行存储为列表中的元素?
我想逐行读取文件,并将每一行附加到列表的末尾。
如何在Python中读取文件的每一行,并将每一行存储为列表中的元素?
我想逐行读取文件,并将每一行附加到列表的末尾。
当前回答
最简单的方法
一个简单的方法是:
将整个文件作为字符串读取逐行拆分字符串
在一行中,这将给出:
lines = open('C:/path/file.txt').read().splitlines()
然而,这是一种非常低效的方式,因为这将在内存中存储两个版本的内容(对于小文件来说可能不是大问题,但仍然如此)。[谢谢Mark Amery]。
有两种更简单的方法:
将文件用作迭代器
lines = list(open('C:/path/file.txt'))
# ... or if you want to have a list without EOL characters
lines = [l.rstrip() for l in open('C:/path/file.txt')]
如果您使用的是Python 3.4或更高版本,最好使用pathlib为文件创建一个路径,该路径可以用于程序中的其他操作:
from pathlib import Path
file_path = Path("C:/path/file.txt")
lines = file_path.read_text().split_lines()
# ... or ...
lines = [l.rstrip() for l in file_path.open()]
其他回答
将文件行读取到列表中的干净和Python方式
首先也是最重要的一点,你应该专注于以一种高效的方式打开文件并阅读其内容。下面是一个我个人不喜欢的方式的例子:
infile = open('my_file.txt', 'r') # Open the file for reading.
data = infile.read() # Read the contents of the file.
infile.close() # Close the file since we're done using it.
相反,我更喜欢以下打开文件的方法,既可以读也可以写非常干净,不需要关闭文件的额外步骤一旦您使用完它。在下面的语句中,我们将打开文件用于读取,并将其分配给变量infile一旦代码在此语句已完成运行,文件将自动关闭。
# Open the file for reading.
with open('my_file.txt', 'r') as infile:
data = infile.read() # Read the contents of the file into memory.
现在我们需要专注于将这些数据引入Python列表,因为它们是可迭代的、高效的和灵活的。在您的案例中,期望的目标是将文本文件的每一行放入一个单独的元素中。为此,我们将使用splitlines()方法,如下所示:
# Return a list of the lines, breaking at line boundaries.
my_list = data.splitlines()
最终产品:
# Open the file for reading.
with open('my_file.txt', 'r') as infile:
data = infile.read() # Read the contents of the file into memory.
# Return a list of the lines, breaking at line boundaries.
my_list = data.splitlines()
测试我们的代码:
文本文件的内容:
A fost odatã ca-n povesti,
A fost ca niciodatã,
Din rude mãri împãrãtesti,
O prea frumoasã fatã.
打印测试报表:
print my_list # Print the list.
# Print each line in the list.
for line in my_list:
print line
# Print the fourth element in this list.
print my_list[3]
输出(因unicode字符而不同):
['A fost odat\xc3\xa3 ca-n povesti,', 'A fost ca niciodat\xc3\xa3,',
'Din rude m\xc3\xa3ri \xc3\xaemp\xc3\xa3r\xc3\xa3testi,', 'O prea
frumoas\xc3\xa3 fat\xc3\xa3.']
A fost odatã ca-n povesti, A fost ca niciodatã, Din rude mãri
împãrãtesti, O prea frumoasã fatã.
O prea frumoasã fatã.
使用此项:
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()获取列表。
使用Python 2和Python 3读写文本文件;它适用于Unicode
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Define data
lines = [' A first string ',
'A Unicode sample: €',
'German: äöüß']
# Write text file
with open('file.txt', 'w') as fp:
fp.write('\n'.join(lines))
# Read text file
with open('file.txt', 'r') as fp:
read_lines = fp.readlines()
read_lines = [line.rstrip('\n') for line in read_lines]
print(lines == read_lines)
注意事项:
with是所谓的上下文管理器。它确保打开的文件再次关闭。这里的所有解决方案,只要简单地生成.strip()或.rstrip(),就无法再现线条,因为它们也会剥离空白。
常用文件结尾
.txt
更高级的文件写入/读取
CSV:超简单格式(读写)JSON:适合编写人类可读数据;非常常用(读写)YAML:YAML是JSON的超集,但更易于阅读(读写,JSON和YAML的比较)pickle:Python序列化格式(读写)MessagePack(Python包):更紧凑的表示(读写)HDF5(Python包):适合矩阵(读写)XML:也存在*叹息*(读写)
对于您的应用程序,以下内容可能很重要:
其他编程语言的支持读/写性能紧凑性(文件大小)
另请参阅:数据序列化格式的比较
如果您正在寻找创建配置文件的方法,您可能需要阅读我的Python配置文件短文。
最简单的方法是:
lines = list(open('filename'))
or
lines = tuple(open('filename'))
or
lines = set(open('filename'))
在set的情况下,我们必须记住,我们没有保留行顺序,并删除重复的行。
下面我添加了@MarkAmery的一个重要补充:
由于您既没有在文件对象上调用.close,也没有使用with语句,因此在某些Python实现中,文件在读取后可能不会关闭,您的进程将泄漏打开的文件句柄。在CPython(大多数人使用的普通Python实现)中,这不是问题,因为文件对象将立即被垃圾收集,这将关闭文件,但通常认为最好的做法是:
with open('filename') as f: lines = list(f)
以确保无论您使用的是什么Python实现,文件都会被关闭。
如果您想从命令行或stdin读取文件,也可以使用fileinput模块:
# reader.py
import fileinput
content = []
for line in fileinput.input():
content.append(line.strip())
fileinput.close()
将文件传递给它,如下所示:
$ python reader.py textfile.txt
在此处阅读更多信息:http://docs.python.org/2/library/fileinput.html