![](/img/trans.png)
[英]I need to read a csv file in python and insert the result into a MYSQL database
[英]I need to read a text file and insert specific values to csv file using python
以下是我要處理的文件
slot : acu:1/1 planned-type : ngfc-f actual-type : ngfc-f oper-status : enabled
error-status : no-error availability : available
alarm-profile : none capab-profile : not_applicable
manufacturer : ALCL
mnemonic : NGFC-F
pba-code :
fpba-code : 3FE64993AABA
fpba-ics : 01
clei-code : VAUCAJ66AA
serial-no : 1743A13DC
failed-test : 00:00:00:00
lt-restart-time : 1970-01-01:05:45:00 lt-restart-cause : timezone_modified lt-restart-num : 0 restart-cnt-per-lt : 0
slot : acu:1/1 planned-type : ngfc-f actual-type : ngfc-f oper-status : enabled
error-status : no-error availability : available
alarm-profile : none capab-profile : not_applicable
manufacturer : ALCL
mnemonic : NGFC-F
pba-code :
fpba-code : 3FE64993AABA
fpba-ics : 01
clei-code : VAUCAJ66AA
serial-no : 1743A13DC
failed-test : 00:00:00:00
lt-restart-time : 1970-01-01:05:45:00 lt-restart-cause : timezone_modified lt-restart-num : 0 restart-cnt-per-lt : 0
我想遍歷文本文件並需要在 CSV 中輸出如下
Slot error-status alarm-profile manufacturer mnemonic
acu:1/1 no-error none ALCL NGFC-F
fopen=open("gthamelslot.txt")
for lines in fopen:
a = lines.strip()
b=a.split()
print(b[0][0])
我堅持這一點。 請幫我弄清楚可以做什么的邏輯
您可以嘗試以下操作。
import re
from collections import defaultdict
import pandas as pd
result = defaultdict(list)
with open('gthamelslot.txt') as f:
for line in f:
match = re.search(r"\s+(\S+)\s+:\s+(\S+)", line)
if match:
k,v = match.group(1), match.group(2)
if k in ["slot", "error-status", "alarm-profile", "manufacturer", "mnemonic"]:
result[k].append(v)
df = pd.DataFrame(result)
print(df)
更新
import re
from collections import defaultdict
import pandas as pd
result = defaultdict(list)
with open('gthamelslot.txt') as f:
for line in f:
match = re.findall(r"\s+(\S+)\s+:\s+(\S+)", line)
for k,v in match:
if k in ["slot", "error-status", "alarm-profile", "manufacturer", "mnemonic", "planned-type"]:
result[k].append(v)
df = pd.DataFrame(result)
print(df)
相應修改
import csv
filepointer = open("file.txt", 'r+')
file = filepointer.readlines()
filelinelist = []
for i in file:
filelinelist.append(i)
firstlist = []
secondlist = []
for line in filelinelist:
lineArray = line.split(":")
first = lineArray[0].strip()
second = lineArray[1].strip()
firstlist.append(first)
secondlist.append(second)
finalList = []
finalList.append(firstlist)
finalList.append(secondlist)
myFile = open('csvfile.csv', 'w')
with myFile:
writer = csv.writer(myFile)
writer.writerows(finalList)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.