Python 读取目录并输出到 CSV

Python Read Directory And Output to CSV

我只是想读取目录并将文件名输出到 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)

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

writer = csv.writer(csvfile)