![](/img/trans.png)
[英]I have a very large xml file (almost 1 gb) I need to split the xml file into 3 smaller files. All with the same headers. I would like to do in Python
[英]I need to split a very large text file
我有一個大文本文件(超過我的RAM),我需要使用它中的每一行進行進一步處理。 但是,如果我一次讀出4096字節的話,我擔心在兩者之間將線分開。 我該怎么辦?
這是你可以做的:
SIZE = 1024
with open('file.txt') as f:
old, data = '', f.read(SIZE)
while data:
# (1)
lines = data.splitlines()
if not data.endswith('\n'):
old = lines[-1]
else:
old = ''
# process stuff
data = old + f.read(SIZE)
data.splitlines(True)
,則新行字符將保留在結果列表中。 使用生成器讀取文件:
def read_file(file_path):
with open(file_path, 'r') as lines:
for line in lines:
yield line
這樣你一次在內存中永遠不會有多行,但仍然會按順序讀取文件。
人們在音頻編碼批次中做這種事情,文件可能很大。 我理解它的正常方法就是有一個內存緩沖區並分兩個階段進行:將任意大小的blob讀入緩沖區(4096或其他),然后從緩沖區中流出字符,對行結尾做出反應。 因為緩沖區是ram,所以逐個字符流式傳輸是很快的。 我不確定在Python中使用哪種數據結構或調用是最好的,我實際上只在C中完成此操作,它只是一塊內存。 但同樣的方法應該有效。
在linux上:
把它放到python腳本中,例如process.py :
import sys
for line in sys.stdin:
#do something with the line, for example:
output = line[:5] + line[10:15]
sys.stdout.write("{}\n".format(output))
要運行該腳本,請使用:
cat input_data | python process.py > output
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.