簡體   English   中英

使用python和pandas從很大的文本文件中提取數據?

[英]Extracting data from a very large text file using python and pandas?

我正在嘗試從一個很大的文本文件(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.')

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.')

您應該使用python生成器。 同時打印會使過程變慢。

以下是一些使用生成器的示例:

Python生成器讀取大型CSV文件

在Python中讀取大文件的惰性方法?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM