![](/img/trans.png)
[英]How to extract data from rows in .csv file into separate .txt files using python?
[英]I want to extract the data from txt files to csv file using python
我想將所有文本文件數據提取到 csv 文件中,並且必須在 python 中繪制圖形。 我知道如何讀取文件,行,在 python 中去除多余的空格,但我不知道從輸入文件中提取數據到輸出文件的邏輯。 我正在附加輸入文件結構的圖像、所需的輸出格式 csv 文件,並且我正在附加我的代碼。 歡迎任何改進代碼的建議。 謝謝你們。
輸入文件
# started on Thu Jan 23 21:03:30 2020
Performance counter stats for './a.out in_5K.fluid in_100K.fluid --verbose':
13.677360 task-clock (msec) # 0.987 CPUs utilized
0 context-switches # 0.000 K/sec
0 cpu-migrations # 0.000 K/sec
1,062 page-faults # 0.078 M/sec
5,86,68,441 cycles # 4.289 GHz
17,13,37,074 instructions # 2.92 insn per cycle
3,14,80,047 branches # 2301.617 M/sec
26,042 branch-misses # 0.08% of all branches
0.013853468 seconds time elapsed
required_output_format.csv
instructions,task-clock (msec),context-switches,cpu-migrations,page-faults,cycles,branches,branch-misses
171337074,13.677360,0,0,1062,58668441,31480047,26042
到目前為止我的代碼:
file = open("input.txt")
lines = file.readlines()
count = 1
for line in lines:
line=line.strip()
if(count>=6 and count <=13 ):
words = line.split('#')
data = words[0].strip().split(" ")
value=""
raw_value = data[0]
values=raw_value.split(',')
for i in values:
value=value+i
print(value.strip() )
heading = data[-2]+data[-1]
print(heading.strip())
count += 1
如果您有多個文件,最好的辦法是有一個循環並使用 csv 編寫器。
import csv
#initialize an array with all the csv files you will write to
txtfiles = ['text1.csv' , 'text2.csv' , '....csv']
csvfiles = ['file1.csv' , 'file2.csv' , '....csv']
for file in txtfiles:
with open( file , 'r') as in_file:
stripped = (line.strip() for line in in_file)
lines = (line.split(",") for line in stripped if line)
#find the corresponding csv file you will write to
csvfile = csvfiles[textfiles.indexof(file)]
with open(csvfile , 'w') as out_file:
writer = csv.writer(out_file)
#Input the header columns here
writer.writerow(('header1' , 'header2' , '...'))
writer.writerows(lines) #The lines is an array of lines that you have stripped
希望這可以幫助!
我認為您在繪制數據時遇到了問題,如果是這樣,那么以 Pandas 數據框的形式導入您的 csv 文件,然后您可以在 python 中輕松繪制
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.