簡體   English   中英

Python3:處理條形分隔文件的最有效方法是什么?

[英]Python3: What is the most efficient way to handle bar delimited files?

我正在嘗試編寫一些可以解析txt文件的東西,看起來像這樣:

TOP1|TOP2|TOP3
Group1|Value2|Value3
Group2|Value2|Value3
TAIL1|TAIL2|TAIL3
  • TOPTAIL將始終是相同的結構,但是Group的結構會發生變化。 IE:每個文件都有自己的組,有自己的值。

  • 這些文件每個只有幾 KB,我需要一種方法將其擴展到 100k+/天的文件解析。

  • 我看過 Hadoop,但不確定它是否適合我的用例。

出於某種原因,我覺得使用一個簡單的方法: with open()並不是最有效的 - 此外,我試圖避免使用 integer 索引來獲取文件屬性。

理想情況下,我想將 map 文件發送到 Python 字典,然后發送到客戶TopTail class。 我還有一個Groups class ,它將是Group下文件中所有行的列表。

結構松散地描述如下: FILE --> [Top, [Group1, Group2], Tail]

到目前為止,我有這個,但它不適合:

with open('file1.txt') as file:
    items = []
    for line in file:
        if not line.strip():
            continue
        d = {}
        data = line.split('|')
        print(data)
        for val in data:
            key, sep, value = val.partition(',')
            d[key.strip()] = value.strip()
        items.append(d)

您可以使用pandas.read_csv()來使用您選擇的分隔符(在本例中為| )讀取文件。


import pandas as pd

df = pd.read_csv('file1.txt, sep="|", engine='python')

暫無
暫無

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

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