我需要逐行读取一个大文件.假设文件超过5GB,我需要读取每一行,但显然我不想使用,readlines()
因为它会在内存中创建一个非常大的列表.
以下代码如何适用于此案例?xreadlines
本身是一个一个地读入记忆吗?是否需要生成器表达式?
f = (line for line in open("log.txt").xreadlines()) # how much is loaded in memory?
f.next()
Run Code Online (Sandbox Code Playgroud)
另外,我可以做什么来以相反的顺序读取它,就像Linux tail
命令一样?
我发现:
http://code.google.com/p/pytailer/
和
两者都运作得很好!
Joh*_*ooy 279
我提供了这个答案,因为Keith虽然简洁,却没有明确地关闭文件
with open("log.txt") as infile:
for line in infile:
do_something_with(line)
Run Code Online (Sandbox Code Playgroud)
Kei*_*ith 53
您需要做的就是使用文件对象作为迭代器.
for line in open("log.txt"):
do_something_with(line)
Run Code Online (Sandbox Code Playgroud)
更好的是在最近的Python版本中使用上下文管理器.
with open("log.txt") as fileobject:
for line in fileobject:
do_something_with(line)
Run Code Online (Sandbox Code Playgroud)
这也会自动关闭文件.
PTB*_*BNL 17
旧学校方法:
fh = open(file_name, 'rt')
line = fh.readline()
while line:
# do stuff with line
line = fh.readline()
fh.close()
Run Code Online (Sandbox Code Playgroud)
Mik*_*ola 15
你最好使用迭代器.相关:http: //docs.python.org/library/fileinput.html
来自文档:
import fileinput
for line in fileinput.input("filename"):
process(line)
Run Code Online (Sandbox Code Playgroud)
这样可以避免一次将整个文件复制到内存中.
请试试这个:
with open('filename','r',buffering=100000) as f:
for line in f:
print line
Run Code Online (Sandbox Code Playgroud)
我不敢相信这会像 @john-la-rooy 的答案看起来那么简单。因此,我cp
使用逐行读写重新创建了该命令。速度太快了。
#!/usr/bin/env python3.6
import sys
with open(sys.argv[2], 'w') as outfile:
with open(sys.argv[1]) as infile:
for line in infile:
outfile.write(line)
Run Code Online (Sandbox Code Playgroud)
如果文件中没有换行符,请执行以下操作:
with open('large_text.txt') as f:
while True:
c = f.read(1024)
if not c:
break
print(c)
Run Code Online (Sandbox Code Playgroud)
过去 6 年里,Fire项目取得了长足的进步。它有一个简单的 API,涵盖了 pandas 功能的有用子集。
dask.dataframe负责内部分块,支持许多可并行操作,并允许您轻松将切片导出回 pandas 以进行内存中操作。
import dask.dataframe as dd
df = dd.read_csv('filename.csv')
df.head(10) # return first 10 rows
df.tail(10) # return last 10 rows
# iterate rows
for idx, row in df.iterrows():
...
# group by my_field and return mean
df.groupby(df.my_field).value.mean().compute()
# slice by column
df[df.my_field=='XYZ'].compute()
Run Code Online (Sandbox Code Playgroud)