【问题标题】:Python Read Directory And Output to CSVPython 读取目录并输出到 CSV
【发布时间】:2021-01-23 14:03:29
【问题描述】:

我只是想读取一个目录并将文件名输出到 csv。目录读取工作正常。当我尝试写入 csv 时,我收到了这个错误。

第 148 行,在 _dict_to_list 中 wrong_fields = rowdict.keys() - self.fieldnames AttributeError: 'str' 对象没有属性 'keys'

import os
import csv

path = 'F:\Production\FocusPoint'
filename = 'storage.csv'
fields = ['Name']

with os.scandir(path) as listOfEntries:
    for entry in listOfEntries:
        if entry.is_file():
            f = (entry.name)

with open(filename,'w', newline='') as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames= fields)
    writer.writeheader()
    writer.writerows(f)

【问题讨论】:

    标签: python csv file output scandir


    【解决方案1】:

    您的变量fields 不是字典。所以csv.DictWriter 将不起作用。怎么样?

    writer = csv.writer(csvfile)
    

    【讨论】:

      猜你喜欢
      • 2015-07-18
      • 1970-01-01
      • 1970-01-01
      • 2021-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-25
      相关资源
      最近更新 更多