我在csv文件中有此文件
Titre,a,b,c,d,e
01,jean,paul,,
01,,,jack,
02,jeanne,jack,,
02,,,jean
我想要:
Titre,a,b,c,d,e
01,jean,paul,jack,
02,jeanne,jack,,jean
你能帮我吗?
答案 0 :(得分:0)
通常,一种好的方法是读取csv文件并使用Python的CSV模块在各行之间进行迭代。
CSV将创建一个迭代器,使您可以像这样循环遍历文件:
import csv
with open('your filename.csv', 'r') as infile:
reader = csv.reader(infile)
for line in reader:
for value in line:
# Do your thing
您将需要构造一个具有不同属性的新数据集。您描述的要求:
我没有为您编写代码的那部分,因为您需要学习和成长。对于初学者来说,这是个好任务。
构建完该数据集后,它将如下所示:
example_processed_data = [["Titre","a","b","c","d","e"],
["01","jean","paul","jack"],
["02","jeanne","jack","","jean"]]
然后您可以创建CSV编写器,并通过遍历该数据来创建外文件,类似于遍历infile的方式:
with open('outfile.csv', 'w') as outfile:
writer = csv.writer(outfile)
for line in example_processed_data:
writer.writerow(line)
print("Done! Wrote", len(example_processed_data), "lines to outfile.csv.")