我正在尝试从很大的文本文件(10Gb)中提取行。文本文件包含工程软件的输出(不是CSV文件)。我想从第1行复制到包含字符串“ stop”的第一行,然后从包含“ restart”的第一行继续到文件末尾。
以下代码可以工作,但是速度很慢(大约一分钟)。有没有更好的方法可以使用熊猫呢?我已经尝试过read_csv函数,但是没有输入分隔符。
file_to_copy = r"C:\Users\joedoe\Desktop\C ANSYS R1\PATCHED\modes.txt"
output = r"C:\Users\joedoe\Desktop\C ANSYS R1\PATCHED\modes_extract.txt"
stop = '***** EIGENVECTOR (MODE SHAPE) SOLUTION *****'
restart = '***** PARTICIPATION FACTOR CALCULATION ***** X DIRECTION'
with open(file_to_copy) as f:
orig = f.readlines()
newf = open(output, "w")
write = True
first_time = True
for line in orig:
if first_time == True:
if stop in line:
first_time = False
write = False
for i in range(300):
newf.write(
'\n -------------------- MIDDLE OF THE FILE -------------------')
newf.write('\n\n')
if restart in line: write = True
if write: newf.write(line)
newf.close()
print('Done.')
答案 0 :(得分:2)
readlines
遍历整个文件。然后,您遍历readlines
的结果。我认为以下编辑将通过大文件为您节省整个迭代。
write = True
first_time = True
with open(file_to_copy) as f, open(output, "w") as newf:
for line in f:
if first_time == True:
if stop in line:
first_time = False
write = False
for i in range(300):
newf.write(
'\n -------------------- MIDDLE OF THE FILE -------------------')
print('\n\n')
if restart in line: write = True
if write: newf.write(line)
print('Done.')
答案 1 :(得分:0)