Python - 从特定列号写入csv

时间:2016-10-17 09:25:39

标签: python csv

我有一个csv文件Temp.csv,我使用以下代码复制到另一个csv文件Final.csv。

dirname = os.path.dirname(os.path.abspath(__file__))
csvfilename = os.path.join(dirname, 'Final.csv')
tempfile = os.path.join(dirname, 'Temp.csv')
with open(csvfilename, 'wb') as output_file:
    writer = csv.writer(output_file, delimiter=',')
    writer.writerow(["Title","This"])
    writer.writerow([])
    with open(tempfile, 'r') as data_file:
        for line in data_file:
            line = line.replace('\n', '')
            row = line.split(",")            
            writer.writerow(row)

代码的最后5行将从A列写入Final.csv文件。我希望它们从D列写入final.csv。此外,我在Temp.csv文件中有多个列。什么是最好的解决方案?使用python 2.7.10。

2 个答案:

答案 0 :(得分:1)

编辑回答评论。您只需要在row

前加3个空字符串
dirname = os.path.dirname(os.path.abspath(__file__))
csvfilename = os.path.join(dirname, 'Final.csv')
tempfile = os.path.join(dirname, 'Temp.csv')
with open(csvfilename, 'wb') as output_file:
    writer = csv.writer(output_file, delimiter=',')
    writer.writerow(["Title","This"])
    writer.writerow([])
    with open(tempfile, 'r') as data_file:
        for line in data_file:
            line = line.replace('\n', '')
            row = line.split(",")
            # there are better ways to do this but this is the most straight forward
            new_row = ['', '', '']
            new_row.extend(row)            
            writer.writerow(new_row)

答案 1 :(得分:0)

您可以尝试:

with open(tempfile, 'r') as data_file:
   for line in data_file:
       line = line.replace('\n', '')
       row = line.split(",")         
       csvfilename.writerow([row[0]+","+row[3]])