![](/img/trans.png)
[英]What is the most efficient way to connect to MySQL across multiple files in Python?
[英]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
TOP
和TAIL
將始終是相同的結構,但是Group
的結構會發生變化。 IE:每個文件都有自己的組,有自己的值。
這些文件每個只有幾 KB,我需要一種方法將其擴展到 100k+/天的文件解析。
我看過 Hadoop,但不確定它是否適合我的用例。
出於某種原因,我覺得使用一個簡單的方法: with open()
並不是最有效的 - 此外,我試圖避免使用 integer 索引來獲取文件屬性。
理想情況下,我想將 map 文件發送到 Python 字典,然后發送到客戶Top
, Tail
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.