用列表替换Python中的第一行
我想要替换我csv文件的第一行。这个csv文件是通过一个脚本生成的,这个脚本会打开其他的csv文件并读取一些列的数据。它的样子是这样的:
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; ...
我想把第一行(时间戳;值;值)替换成我保存在一个列表里的名字。
我想要的输出应该是:
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; ...
我该怎么做呢?
为了更具体一点,这是我用来生成csv文件的代码:
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)
现在问题是,当我写row[15]的时候,我只是从一个文件中复制了一列,那个列的样子是:
Value;
1,956;
1;054;
1,456;
我想把值替换成我在namelist中保存的文件名的一部分。
2 个回答
1
一般来说,处理这个问题的步骤是:先打开要读取的文件,跳过旧的标题行,然后打开目标文件准备写入,写入新的标题行,接着把文件剩下的内容复制过来。最后,把新文件重命名为旧文件的名字。
import os
new_headers = ['TimeStampfromlist', 'Firstnamefromlist', 'Secondnamefromlist']
filename = 'data.csv'
with open(filename, 'r') as lines:
next(lines) # Skip first line.
tmp_filename = filename + '.tmp'
with open(tmp_filename, 'w') as out_file:
out_file.write(':'.join(new_headers) + '\n')
out_file.writelines(lines)
os.rename(tmp_filename, filename)
4
你可以使用 csv
模块,但这个逻辑也能满足你的需求。
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)