【问题标题】:Python Dictionary, structure of folder and files but in two dictionariesPython字典,文件夹和文件的结构,但在两个字典中
【发布时间】:2013-11-09 13:50:07
【问题描述】:

我正在寻找一种算法来完成一项工作。基本上我从用户那里得到一个输入,即源目录。我想创建两个不同的字典,一个包含文件夹的子文件夹,一个包含文件夹的文件。 例如:

我有一个文件夹“文件夹”,其中包含一个名为:log.txt 的文本文件和 3 个子文件夹,文件夹 1、文件夹 2 和文件夹 3。在文件夹 2 中有另一个名为 txt1.txt 的文本文件和另一个名为 subfolder 的文件夹,在这个子文件夹中有一个名为:pic.png 的图片

folder->log.txt, folder1, folder2->(txt.txt, subfolder->pic.png), folder3

我想要的是一个看起来像这样的字典:

folders = {'folder1':'', 'folder2': 'subfolder', folder3}
files = {'log.txt':'', 'txt.txt': 'folder2', 'pic.png':'folder2/subfolder'}

一般来说,我需要一个清晰的文件夹和子文件夹字典,以便在正确创建文件夹和子文件夹后轻松。然后文件的字典要清楚文件在哪里。如果您有其他结构的文件字典没关系,如果您认为更容易和快速。 提前谢谢你。

编辑:我正在使用 python 3 运行 Mac OS X

编辑 2:

dirs = [d for d in os.listdir(source) if os.path.isdir(os.path.join(source, d))]

for folder in dirs:
    tmp_source = source + folder
    dirs2 = [d for d in os.listdir(tmp_source) if os.path.isdir(os.path.join(tmp_source, d))]
    if dirs2 != []:
       print('Folder: ', dirs2, 'is not empty')

    dic[folder] = dirs2

【问题讨论】:

  • 你复制内容吗?如果是这样,你不是invent tar吗?
  • 我想按照自己的方式使用字典。我不想要一个内置功能。提前谢谢你。

标签: python file python-3.x dictionary directory


【解决方案1】:

下面的代码将递归遍历根文件夹,并将每个文件夹(包括根文件夹)的文件名保存在一个字典中,其中键为文件夹路径。

import os

root_folder = r'C:\Users\Steinar\Google Drive\Kode\Ymse\test\test'
content = {}

for root, dirs, files in os.walk(root_folder):
    for subdir in dirs:
        content[os.path.join(root, subdir)] = []
    content[root] = files

# Print out the content dict    
for folder, filenames in content.items():
    print 'Folder: {}'.format(folder)
    print 'Filenames:'
    for filename in filenames:
        print '-> {}'.format(filename)

使用上述输入,此脚本会输出正确的文件夹结构。

Folder: C:\Users\Steinar\Google Drive\Kode\Ymse\test\test\test2
Filenames:
-> test2.txt
Folder: C:\Users\Steinar\Google Drive\Kode\Ymse\test\test
Filenames:
-> test.txt
Folder: C:\Users\Steinar\Google Drive\Kode\Ymse\test\test\test2\test3\test4
Filenames:
Folder: C:\Users\Steinar\Google Drive\Kode\Ymse\test\test\test2\test3
Filenames:
-> test3.txt

如果你想重建文件夹结构,你可以遍历content.keys(),然后创建每个文件夹。

【讨论】:

  • 谢谢,但我收到此错误:Traceback(最近一次调用最后一次):文件“/Users/username/Desktop/app.py”,第 42 行,在 strr = os. path.walk(source_dir, store_fnames, None) AttributeError: 'module' object has no attribute 'walk'
  • 记得像这样解析你的文件夹字符串:r'C:\path\etc\',和import os
  • 好吧,那么你应该检查你的 Python 安装。此代码在 Python 2.7 上测试。
  • @iCyprus 阅读了我和 Steinar Lima 的 cmets 中的两个附加链接。
  • 好吧,我更新了答案,但你真的应该尝试自己做点什么。如果您使用代码,应该不难理解应该如何解决这个问题。你有没有尝试过任何东西?如果您需要更多帮助,请向我们提供一些代码,表明您至少尝试过自己理解我们的建议。
猜你喜欢
  • 1970-01-01
  • 2016-03-07
  • 1970-01-01
  • 1970-01-01
  • 2014-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多