[英]I want to extract the data from txt files to csv file using python
I want to extract all the text files data into csv files and have to plot the graphs in python.我想将所有文本文件数据提取到 csv 文件中,并且必须在 python 中绘制图形。 I know how to read the file, lines , stripping out extra spaces in python but I don't know the logic to extract the data from input files to output file.
我知道如何读取文件,行,在 python 中去除多余的空格,但我不知道从输入文件中提取数据到输出文件的逻辑。 I am attaching the images of input file structure, required output format csv file and also I am attaching my code.
我正在附加输入文件结构的图像、所需的输出格式 csv 文件,并且我正在附加我的代码。 any suggestion to improve code is welcome.
欢迎任何改进代码的建议。 Thank you guys.
谢谢你们。
input.txt输入文件
# 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 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
My code so far:到目前为止我的代码:
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
If you have multiple files, the best thing would be to have a loop and use a csv writer.如果您有多个文件,最好的办法是有一个循环并使用 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
Hope this helps!希望这可以帮助!
我认为您在绘制数据时遇到了问题,如果是这样,那么以 Pandas 数据框的形式导入您的 csv 文件,然后您可以在 python 中轻松绘制
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.