【问题标题】:Python: Write the data into multiple columns of output filePython:将数据写入输出文件的多列
【发布时间】:2018-11-15 07:38:01
【问题描述】:

我正在编写一个 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 的第二列应该怎么做

【问题讨论】:

    标签: csv python-3.5 read-write


    【解决方案1】:
    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-18
      • 2019-10-12
      相关资源
      最近更新 更多