python - 遍历字典以创建 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 文件中只有一项的键/值对。
解决方案
由于 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)
推荐阅读
- python - 自定义用户的显示表单
- json - 在java中结合rows属性?
- python - 如何通过匹配我创建的 max_min 变量中的索引来使用字典创建数据框
- c# - 为什么在统一编辑器窗口脚本中制作新的颜色实例时它不会改变颜色?
- material-ui - material-ui textField 颜色
- javascript - 从异步函数返回查询对象时,如何防止 Knex.js 运行查询对象?
- angular - 如何跨模块共享 utils 类
- ios - 如何使用 Xamarin iOS 发送具有不同类别标识符的多个通知?
- angular - 是否可以从 Angular Schematic 中执行 shell 命令?
- java - 如何在使用 HashSet 时维护插入顺序?