我有一个非常大的4GB文件,当我试图读取它时,我的电脑挂了。 所以我想一块一块地读取它,在处理每一块之后,将处理过的一块存储到另一个文件中,然后读取下一块。
有什么方法可以生产这些碎片吗?
我喜欢有一个懒惰的方法。
我有一个非常大的4GB文件,当我试图读取它时,我的电脑挂了。 所以我想一块一块地读取它,在处理每一块之后,将处理过的一块存储到另一个文件中,然后读取下一块。
有什么方法可以生产这些碎片吗?
我喜欢有一个懒惰的方法。
当前回答
在Python 3.8+中,你可以在while循环中使用.read():
with open("somefile.txt") as f:
while chunk := f.read(8192):
do_something(chunk)
当然,你可以使用任何你想要的块大小,你不需要使用8192(2**13)字节。除非你的文件大小恰好是你的块大小的倍数,否则最后一个块将小于你的块大小。
其他回答
File.readlines()接受一个可选的size参数,它近似于在返回的行中读取的行数。
bigfile = open('bigfilename','r')
tmp_lines = bigfile.readlines(BUF_SIZE)
while tmp_lines:
process([line for line in tmp_lines])
tmp_lines = bigfile.readlines(BUF_SIZE)
如果您的计算机、操作系统和python是64位的,那么您可以使用mmap模块将文件的内容映射到内存中,并使用索引和切片访问它。下面是文档中的一个例子:
import mmap
with open("hello.txt", "r+") as f:
# memory-map the file, size 0 means whole file
map = mmap.mmap(f.fileno(), 0)
# read content via standard file methods
print map.readline() # prints "Hello Python!"
# read content via slice notation
print map[:5] # prints "Hello"
# update content using slice notation;
# note that new content must have same size
map[6:] = " world!\n"
# ... and read again using standard file methods
map.seek(0)
print map.readline() # prints "Hello world!"
# close the map
map.close()
如果你的计算机、操作系统或python是32位的,那么映射大文件会占用你的大部分地址空间,并耗尽程序的内存。
在Python 3.8+中,你可以在while循环中使用.read():
with open("somefile.txt") as f:
while chunk := f.read(8192):
do_something(chunk)
当然,你可以使用任何你想要的块大小,你不需要使用8192(2**13)字节。除非你的文件大小恰好是你的块大小的倍数,否则最后一个块将小于你的块大小。
我认为我们可以这样写:
def read_file(path, block_size=1024):
with open(path, 'rb') as f:
while True:
piece = f.read(block_size)
if piece:
yield piece
else:
return
for piece in read_file(path):
process_piece(piece)
参考python的官方文档https://docs.python.org/3/library/functions.html#iter
也许这个方法更python化:
"""A file object returned by open() is a iterator with
read method which could specify current read's block size
"""
with open('mydata.db', 'r') as f_in:
block_read = partial(f_in.read, 1024 * 1024)
block_iterator = iter(block_read, '')
for index, block in enumerate(block_iterator, start=1):
block = process_block(block) # process your block data
with open(f'{index}.txt', 'w') as f_out:
f_out.write(block)