簡體   English   中英

從多個文本文件中提取特定數據並將它們寫入 csv 中的列

[英]Extracting specific data from multiple text files and writing them into columns in csv

我正在嘗試編寫一個代碼,該代碼將從多個報告文件中搜索特定數據,並將它們寫入單個 csv 的列中。

我正在尋找的報告文件行並不總是在同一行,所以我正在尋找與以下行相關的數據:

估計文件:pog_example.bef

估計 ID:o1_p1

估計為 61078 (100.0%)。

我想將每個文本文件中的數據寫入 csv 的列中,如下所示:

example.bef, o1_p1, 61078 (100.0%) 估計

到目前為止,我有這個腳本,它將列出我的第一個條件,但我不知道如何循環它以找到我的第二行和第三行來填充第二列和第三列

from glob import glob
import fileinput
import csv

with open('percentage_estimated.csv', 'w', newline='') as est_report:
    writer = csv.writer(est_report)
    for line in fileinput.input(glob('*.bef*')):

        if 'Estimate file' in line:
            writer.writerow([line.split('pog_')[1].strip()]) 

我對 python 很陌生,所以任何幫助將不勝感激!

您已經很接近了,只是為了提高可讀性而進行了一些重組,最重要的是,獲得了打開文件的正確方式和順序,然后遍歷其行:

from glob import glob
import csv

# Don't worry about `with open()` here, it's only one file and will close when prog ends
est_report = open('percentage_estimated.csv', 'w', newline='')
writer = csv.writer(est_report)

for fname in glob('*.bef*'):
    # Here, `with open()` is better, iterating through numerous files
    with open(fname) as bef_file:
        for line in bef_file:
            if 'Estimate file' in line:
                writer.writerow([line.split('pog_')[1].strip()])

如果有人想看看最終對我有用的東西

from glob import glob
import csv

all_rows = []

with open('percentage_estimated.csv', 'w', newline='') as bef_report:
    writer = csv.writer(bef_report)
    writer.writerow(['File name', 'Est ID', 'Est Value'])
    for file in glob('*.bef*'):
        with open(file,'r') as f:
            for line in f:
                if 'Estimate file' in line:
                    fname = line.split('pog_')[1].strip()
                    line = next(f)
                    est_id = line.split('Estimate ID:')[1].strip()
                    line = next(f)
                    line = next(f)
                    line = next(f)
                    line = next(f)
                    line = next(f)
                    line = next(f)
                    line = next(f)
                    value = line.strip()
                    row = [fname, est_id, value]
                    all_rows.append(row)
                    break  
            writer.writerows(all_rows)

暫無
暫無

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

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