我有一个大文件,例如XXX_USR.txt。我遍历该文件夹,并且某些txt文件的大小超过500 MB。为了避免MEMORY ERROR
,我需要逐行附加文件。但是,我当前的方法太慢了。第一行由|SYS
附加,所有其他行由'| ' + amendtext
附加。 amendtext
是一个变量,它从.txt文件的名称中获取第一个下划线之前的第一个字符串,例如“ XXX”。
File: XXX_USR.txt
INPUT:
| name | car |
--------------
| Paul |Buick|
|Ringo |WV |
|George|MG |
| John |BMW |
DESIRED OUTPUT:
|SYS | name | car |
--------------------
| XXX | Paul |Buick|
| XXX |Ringo |WV |
| XXX |George|MG |
| XXX | John |BMW |
我的代码太慢了,但是遇到了内存错误。
import os
import glob
from pathlib import Path
cwd = 'C:\\Users\\EricClapton\\'
directory = cwd
txt_files = os.path.join(directory, '*.txt')
for txt_file in glob.glob(txt_files):
cpath =(Path(txt_file).resolve().stem)
nametxt = "-".join(cpath.split('_')[0:1])
amendtext = "| " + nametxt
systext = "| SYS"
with open(txt_file,'r', errors='ignore') as f:
get_all=f.readlines()
with open(txt_file,'w') as f:
for i,line in enumerate(get_all,1):
if i == 1:
f.writelines(systext + line)
else:
f.writelines(amendtext + line)
太慢了,你到底是什么意思?它可以在几秒钟或几分钟内运行吗?我可以说我在笔记本电脑上运行了类似的情况,文件超过1G和35946689行,大约花费了29s。
我使用in-place模块以edit-type模式而不是read
和/或write
打开文件。这样就无需在处理数据时重复存储数据。
with in_place.InPlace(txt_file) as f:
for line in f:
f.write(amendtext + line)