未加星标

Replace the first line of Python with the list

字体大小 | |
[开发(python) 所属分类 开发(python) | 发布者 店小二05 | 时间 2018 | 作者 红领巾 ] 0人收藏点击收藏

I would like to replace the first row of my csv file. The csv file is generated by a script that opens other csv files and reads some columns. It looks like

TimeStamp;Value;Value; ... 2014/08/04 21:00:53.575;0.168889;1.146; ... 2014/08/04 21:01:23.590;0.168889;1.138; ... 2014/08/04 21:01:53.595;0.17;1.154; ... 2014/08/04 21:02:23.585;0.168889;1.205; ...

I would like to replace the first row (Timestamp;Value;Value) with the names is saved in a list.

The output I want should be

TimeStampfromlist;Firstnamefromlist;Secondnamefromlist; ... 2014/08/04 21:00:53.575;0.168889;1.146; ... 2014/08/04 21:01:23.590;0.168889;1.138; ... 2014/08/04 21:01:53.595;0.17;1.154; ... 2014/08/04 21:02:23.585;0.168889;1.205; ...

How can I do that?

Trying to be more specific this is the code I use to generate my csv file

import csv import glob import os, sys path = "C:/Users/ButoeruG/Desktop/pythonscripts/prova" dirs = glob.glob('*.csv') namelist = dirs print dirs[0] file1 = dirs[1] print file1 for file in namelist: namelist = file.partition("TrendLogExtended_")[2].partition("-Ext).csv")[0] print namelist primofile = csv.reader(open(file1, 'rb'), delimiter=";", quotechar='|') output_rows = [] for row in primofile: output_rows.append([row[2], row[15]]) for file in dirs: data = csv.reader(open(file, 'rb'), delimiter=";", quotechar='|') column = [] for idx,row in enumerate(data): output_rows[idx].append(row[15]) with open("provaoutput.csv", 'wb') as f: writer = csv.writer(f, delimiter=';') for row in output_rows: writer.writerow(row) Now the point is that when I write the row[15] I just copy from a file a column that looks like: Value; 1,956; 1;054; 1,456;

I would like to replace value with part of the file name that I saved in namelist.

You can use the the csv module but this logic will do what you need.

l = ["TimeStampfromlist","Firstnamefromlist","Secondnamefromlist"] with open("in.csv", 'r') as data_file: lines = data_file.readlines() lines[0]= ":".join(l)+"\n" # replace first line, the "header" with list contents with open("in.csv", 'w') as out_data: for line in lines: # write updated lines out_data.write(line)

本文开发(python)相关术语:python基础教程 python多线程 web开发工程师 软件开发工程师 软件开发流程

代码区博客精选文章
分页:12
转载请注明
本文标题:Replace the first line of Python with the list
本站链接:https://www.codesec.net/view/611537.html


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 开发(python) | 评论(0) | 阅读(56)