Python:将数据写入输出文件的多列

时间:2018-06-05 18:14:02

标签: csv python-3.5 read-write

我正在编写一个python解决方案来读取名为Input.txt(tsv)的文件的第一列,并写入名为Output.txt(tsv)的文件。

    import csv

    with open('Input.txt', 'r') as rf:
        reader = csv.reader(rf, delimiter='\t')

        with open('Output.txt', 'w') as wf:
            writer = csv.writer(wf, delimiter='\t')

            desired_column = [0]

            for line in reader:
                Column1 = list(line[i] for i in desired_column)
                writer.writerow(Column1)

上面的代码读取Input.txt的第一列并写入Output.txt的第一列。

我的问题是:如果我想将相同的数据写入Output.txt的第二列

,我该怎么办?

1 个答案:

答案 0 :(得分:0)

import csv

with open('Input.txt', 'r') as rf:
    reader = csv.reader(rf, delimiter='\t')

    with open('Output.txt', 'w') as wf:
        writer = csv.writer(wf, delimiter='\t')

        desired_column = [0]
        for line in reader:
            Column1 = list(line[i] for i in desired_column)
            '''We can use writerows function to zip the value. Instead of
               different column name , we can use same copied column to satisfy your requirement'''   
            writer.writerows(zip(Column1 ,Column1 ))

希望这符合您的要求。请参阅https://docs.python.org/2/library/csv.html#csv.csvwriter.writerows