一个例子。我有一个CSV文件如下:
10,20,30,-40,50
20,30,40,-50,60
30,40,50,-60,70
基本上我需要在列中翻转数字的符号。任何专栏。在这个例子中,第4和第5的迹象......
10,20,30,40,-50
20,30,40,50,-60
30,40,50,60,-70
将它们打印到新文件中。
我可以在CSV文件中阅读,但说实话,我不知道从哪里开始。任何帮助将不胜感激。
答案 0 :(得分:0)
逐行读入文件,并按CSV分隔符拆分。结果列表的顺序将按列的顺序排列(即,splitline [0]是您的第一个csv列,等等)。然后,您可以将该行写入新文件并相应地修改数据。在你的情况下,我相信你希望最后两个值乘以负数。
答案 1 :(得分:0)
使用csv
lib来解析您的文件:
import csv
with open("in.csv") as f, open("new.csv","w") as tmp:
r = csv.reader(f)
wr = csv.writer(tmp)
# wr.writerow(next(r)) # uncomment if file has header
# (*_ -> all but last two), (a, b -> second last and last value)
# -- == +, -+ == -
wr.writerows(_ + [-int(a), -int(b)] for *_, a, b in r:)
输入:
10,20,30,-40,50
20,30,40,-50,60
30,40,50,-60,70
输出:
10,20,30,40,-50
20,30,40,50,-60
30,40,50,60,-70
如果你想要第n列只是改变解压缩的方式:
wr.writerows([a, b, c , -int(d), -int(e)] + _ for a, b, c, d, e,*_ in r:)
^^ ^^
4th 5th
wr.writerows([-int(a),b, -int(c), d, e] + _ for a, b, c, d, e,*_ in r:)
^^ ^^
1st 3rd
如果你有41列并且想要改变,33,39,40,41:
with open("in.csv") as f, open("out.csv","w") as tmp:
r = csv.reader(f)
wr = csv.writer(tmp)
for *_, t_3, a, b, c, d, e, t_9, ft_0, ft_1 in r:
wr.writerow(_ + [-int(t_3), a, b, c, d, e, -int(t_9), -int(ft_0), -int(ft_1)])