【问题标题】:python csv write only certain fieldnames, not allpython csv只写某些字段名,而不是全部
【发布时间】:2012-03-29 00:55:25
【问题描述】:

我一定错过了什么,但我不明白。我有一个 csv,它有 1200 个字段。我只对 30 感兴趣。你如何让它发挥作用?我可以读/写整个shebang,没关系,但我真的很想写出30个。我有一个字段名列表,我有点破解标题。

我将如何翻译以下内容以使用 DictWriter/Reader?

for file in glob.glob( os.path.join(raw_path, 'P12*.csv') ):
    fileReader = csv.reader(open(file, 'rb'))
    fileLength = len(file)
    fileGeom = file[fileLength-7:fileLength-4]
    table = TableValues[fileGeom]
    filename = file.split(os.sep)[-1]
    with open(out_path + filename, "w") as fileout:
        for line in fileReader:
            writer = csv.writer(fileout, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
            if 'ID' in line:
                outline = line.insert(0,"geometryTable")
            else:
                outline = line.insert(0,table) #"%s,%s\n" % (line, table)
            writer.writerow(line)

【问题讨论】:

    标签: python csv


    【解决方案1】:

    这是一个使用DictWriter 仅写出您关心的字段的示例。我将把移植工作留给你:

    import csv
    
    headers = ['a','b','d','g']
    
    with open('in.csv','rb') as _in, open('out.csv','wb') as out:
        reader = csv.DictReader(_in)
        writer = csv.DictWriter(out,headers,extrasaction='ignore')
        writer.writeheader()
        for line in reader:
            writer.writerow(line)
    

    in.csv

    a,b,c,d,e,f,g,h
    1,2,3,4,5,6,7,8
    2,3,4,5,6,7,8,9
    

    结果(out.csv)

    a,b,d,g
    1,2,4,7
    2,3,5,8
    

    【讨论】:

    • 完美。之前,我错过了extrasaction。这会删除...额外的东西吗?我也试图限制读取的字段,但这并没有让我到任何地方。 tho,是否可以限制阅读?例如fileReader = csv.DictReader(open(file, 'rb'), fieldnames=EstimateColumns)
    • DictReader 读取所有列。如果字典(行)的键多于标题列表中指定的键,则 dict writer 的默认设置是抛出异常。 extrasaction='ignore' 抑制了这一点。 DictReader 总是读取整个 csv 行。它确实需要一个字段名称参数,但如果使用它指定列名称,而不是使用 csv 的第一行作为列名称。见docs.python.org/library/csv.html#csv.DictReader
    • 在上面的代码中,我们可以在哪里为行添加过滤器? for example, remove rows where column-g==7
    • @Prem 在 for 之后,使用 if line['g'] != 7: 限定写入。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-03
    • 2022-12-22
    • 2017-10-08
    • 2020-03-14
    • 1970-01-01
    • 1970-01-01
    • 2012-07-21
    相关资源
    最近更新 更多