简体   繁体   中英

Python Read Directory And Output to CSV

I am just trying to read a directory and out put the file names to a csv. The directory read works fine. It is when I try to write to the csv that I am getting this error.

line 148, in _dict_to_list wrong_fields = rowdict.keys() - self.fieldnames AttributeError: 'str' object has no attribute '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)

Your variable fields is not a dictionary. So csv.DictWriter will not work. How about?

writer = csv.writer(csvfile)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM