![](/img/trans.png)
[英]Convert CSV to JSON with python and split the csv with seperator "|"
[英]python 3.8 how to convert txt to csv with seperator of 2 or more spaces
我正在嘗試使用 Python 從遠程登錄 session 轉換 txt 導出。 txt看起來像這樣
LocalPort ChassisId PortId PortDescr SysName
--------- + ------------------------- ------ --------- ----------------------
3 01 23 45 67 89 76 1 1 name1
19 01 23 45 67 89 76 19 19 name2
21 01 23 45 67 89 76 9 9 name3
22 01 23 45 67 89 76 22 22 name4
22 01 23 45 67 89 76 LAN-1 example name5
23 01 23 45 67 89 76 LAN-1 example name6
23 01 23 45 67 89 76 23 23 name7
所以我用 python 嘗試了類似的方法:
read_file = pd.read_csv(OUTPUT_FILE_PROCESSED_TXT, sep="\s{2,}", header=5)
read_file.to_csv(OUTPUT_CSV, sep=",", header=["LocalPort","ChassisId","PortId","PortDescr","SysName"])
但結果是我在生成的 csv 中遺漏了 LocalPort 3 和 LocalPort 22 之間的很大一部分。 這些行被刪除。 所以我的 csv 只有標題和最后三行。
誰能幫助我,也許可以解釋為什么 Python 正在刪除一些行? 我知道其他人問了類似的問題,但解決方案對我沒有幫助
提前致謝...
您可以手動解析該OUTPUT_FILE_PROCESSED_TXT
文件:
import re
with open(OUTPUT_FILE_PROCESSED_TXT, "r") as f:
telnet_output = f.read()
rows = telnet_output.splitlines()
values = [re.split(r"\s{2,}", row.strip()) \ # split when >2 spaces
for row in rows[1:] \ # avoid header row
if not row.strip().startswith("-") and row] # avoid empty and --- rows
columns = rows[0].split()
df = pd.DataFrame(values, columns=columns)
檢查您的df
是否定義明確:
>>> print(df)
LocalPort ChassisId PortId PortDescr SysName
0 3 01 23 45 67 89 76 1 1 name1
1 19 01 23 45 67 89 76 19 19 name2
2 21 01 23 45 67 89 76 9 9 name3
3 22 01 23 45 67 89 76 22 22 name4
4 22 01 23 45 67 89 76 LAN-1 example name5
5 23 01 23 45 67 89 76 LAN-1 example name6
6 23 01 23 45 67 89 76 23 23 name7
現在按照您的建議導出到csv
:
df.to_csv(OUTPUT_CSV, sep=",")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.