使用python分割大文件
Split large files using python
我在尝试拆分大文件(例如,大约 10GB)时遇到了一些麻烦。基本思想是简单地读取行,并将每行(例如 40000 行)分组到一个文件中。
但是有两种"读取"文件的方式。
1) 第一个是一次读取整个文件,并把它变成一个LIST。但这需要将整个文件加载到内存中,这对于太大的文件来说是很痛苦的。 (我想我以前问过这样的问题)
在 python 中,我试过一次读取整个文件的方法包括:
|
1
2 3 4 5 6 |
input1=f.readlines()
input1 = commands.getoutput('zcat ' + file).splitlines(True) input1 = subprocess.Popen(["cat",file], |
好吧,那么我可以很容易地将 40000 行分组到一个文件中:
或者使用列表的好处是我们可以很容易地指向特定的行。
2)第二种方式是逐行读取;读取时处理该行。那些读取的行不会保存在内存中。
示例包括:
|
1
2 |
f=gzip.open(file)
for line in f: blablabla... |
或
|
1
|
for line in fileinput.FileInput(fileName):
|
我确定对于 gzip.open,这个 f 不是一个列表,而是一个文件对象。似乎我们只能逐行处理;那么我该如何执行这个"拆分"工作呢?如何指向文件对象的特定行?
谢谢
相关讨论
- 当你想到它时..你不能。只有在阅读了所有前面的行并计算了换行符(\\
)。 (忽略特殊情况,这是一个奇怪的文件,其中每一行的长度都是已知的。)
|
1
2 3 4 5 6 7 8 9 10 11 |
NUM_OF_LINES=40000
filename = 'myinput.txt' with open(filename) as fin: fout = open("output0.txt","wb") for i,line in enumerate(fin): fout.write(line) if (i+1)%NUM_OF_LINES == 0: fout.close() fout = open("output%d.txt"%(i/NUM_OF_LINES+1),"wb") fout.close() |
相关讨论
-
如果您希望文件中恰好有 40,000 行,我认为您应该将
i 初始化为0 ,而不是1 。 - 你需要什么包?
-
@LuisFelipe 不需要外部包,
fileinput 是一个内置包,甚至不需要此功能,您也可以使用普通的open() - 我尝试了相同的代码,它说"名称'文件名'未定义"
-
@LuisFelipe
filename 是一个变量,应该包含输入文件的路径 - @yurib 抱歉,我在评论其他问题哈哈
如果每个文件中有特定数量的文件行没有什么特别之处,
If given an optional parameter sizehint, it reads that many bytes from
the file and enough more to complete a line, and returns the lines
from that. This is often used to allow efficient reading of a large
file by lines, but without having to load the entire file in memory.
Only complete lines will be returned.
...所以你可以这样写代码:
|
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
# assume that an average line is about 80 chars long, and that we want about
# 40K in each file. SIZE_HINT = 80 * 40000 fileNumber = 0 |
相关讨论
- -1(1)您没有明确关闭输出文件(2)以文本模式读取并以二进制模式写入保证"如果我们在 Windows 上,则可以修改"
|
1
2 3 4 5 6 7 8 |
chunk_size = 40000
fout = None for (i, line) in enumerate(fileinput.FileInput(filename)): if i % chunk_size == 0: if fout: fout.close() fout = open('output%d.txt' % (i/chunk_size), 'w') fout.write(line) fout.close() |
相关讨论
-
if fout: fout.close() 退出循环后需要执行
对于一个 10GB 的文件,第二种方法显然是要走的路。以下是您需要做的概要:
相关讨论
if num_lines % 4000 == 0: avoid_writing_empty_file_at_end() # except when numlines == 0
我找到的最佳解决方案是使用库 filesplit (https://pypi.org/project/filesplit/)。
您只需要指定输入文件、输出文件夹和所需的输出文件大小(以字节为单位)。最后,图书馆将为您完成所有工作。
|
1
2 3 4 5 6 |
from fsplit.filesplit import Filesplit
fs = Filesplit() def split_cb(f, s): print("file: {0}, size: {1}".format(f, s)) fs.split(file="/path/to/source/file", split_size=900000, output_dir="/pathto/output/dir", callback=split_cb) |
显然,当您对文件进行处理时,您将需要以某种方式迭代文件的内容——无论您是手动执行还是让 Python API 的一部分为您执行(例如 readlines () 方法) 并不重要。在大 O 分析中,这意味着您将花费 O(n) 时间(n 是文件的大小)。
但是将文件读入内存也需要 O(n) 空间。虽然有时我们确实需要将 10 gb 的文件读入内存,但您的特定问题不需要这样做。我们可以直接遍历文件对象。当然,文件对象确实需要空间,但我们没有理由将文件内容以两种不同的形式保存两次。
因此,我会选择您的第二个解决方案。