首页 > 解决方案 > 遍历字典以创建 csv 文件

问题描述

我正在尝试编写一个 python 3.6 脚本,它将键/值对从文件夹树字典添加到 csv 文件。文件夹三中的文件是键,它们的路径是值。

我遍历字典的方式似乎存在错误,因为在 csv 文件中,我只从其中一个文件夹中获取键/值对,而不是整个文件夹树。我只是看不到我的错误在哪里。这是我的代码:

import os
import csv

root_dir = '.'

for root, dirs, files in os.walk (root_dir, topdown='true'):
     folder_dict = {filename:root for filename in files}
     print (folder_dict)

with open ('test.csv', 'w') as csvfile:
     for key in folder_dict:
         csvfile.write ('%, %s\n'% (key, folder_dict [key]))

我得到了字典,但在 csv 文件中只有一项的键/值对。

标签: pythoncsvdictionarydirectorytree

解决方案


由于 line folder_dict = {filename:root for filename in files},您会覆盖每个循环上的数据,将最后一个字典作为稍后写入 CSV 的唯一内容。

您根本不需要这种临时数据结构。只需在发现要写入的文件时写入 CSV。您实际上并未使用 CSV 模块,因此我将其添加到解决方案中。

import os
import csv

root_dir = '.'

with open ('test.csv', 'w') as fileobj:
    csvfile = csv.writer(fileobj)
    for root, dirs, files in os.walk (root_dir, topdown='true'):
        csvfile.writerows((filename, root) for filename in files)

推荐阅读