【问题标题】:CSV file based on other files data基于其他文件数据的 CSV 文件
【发布时间】:2015-03-12 17:48:14
【问题描述】:

我想在 Python 中执行此操作。

给定两个输入 CSV 文件 (data1.csv) 和 (data2.csv) 生成一个遵循这些规范的新文件 (sample.csv):

  • data1.csv 在文件的第一行有标题
  • data2.csv 在文件的第一行有标题
  • data1.csv 的列数比 data2.csv 多

  • sample.csv 应该包含 data1.csv 中的所有行,但只有那些 出现在 data2.csv 中,并按照它们出现在 data2.csv 中的顺序

示例:

 data1.csv
 h1,h2,h3,h4,h5,h6
 0,1,2,3,4,5
1,2,3,4,5,6

data2.csv
h1,h4,h3,h6
0,1,2,3

sample.csv
h1,h4,h3,h6
0,3,2,5
1,4,3,6

 My code:

   import csv
    import array
   import os

  with open('C:\\Users\\nithin\\Desktop\\data1.csv') as f:
     r = csv.reader(f, delimiter=',')
    dict1 = {row[0]: row[1:] for row in r if (row[0]=='h1')}

   print str(dict1)

【问题讨论】:

    标签: python file csv import-from-csv


    【解决方案1】:

    这使工作:

    import csv
    with open('/tmp/data2.csv') as f:
        headerList = f.readline().split(",")
    with open('/tmp/data1.csv') as f:
        r = csv.DictReader(f, delimiter=',')
        with open('/tmp/sample.csv', 'w') as fout:
            fout.write(','.join(headerList))
            for row in r:
                lineTab = [row[head.rstrip()] for head in headerList]
                fout.write(",".join(lineTab)+"\n")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-27
      • 2019-03-03
      • 2015-11-23
      • 2018-11-29
      • 1970-01-01
      • 1970-01-01
      • 2021-10-08
      • 1970-01-01
      相关资源
      最近更新 更多