文件名及其路径为字典未显示所有结果

问题描述 投票:1回答:1

我有带路径的文本文件,例如:

/path/to/file.ext

我需要将这些路径拆分为字典,以便key将路径排除文件和value - 文件名及其扩展名。我用以下代码管理了这个:

base = {}
with open ('text.txt') as f:
    for line in f:
        key,val = line.strip('\n').rsplit('/',1)
        base[key] = val

我已经使用.strip('\n')去除换行符和.rsplit('/',1)根据路径中的最后一个/分割我的整个路径。

代码基本上工作,但是...它不处理整个txt文件。

处理9900+路径的文件,我的基础少于3000个元素(键+值)。我用len(base)检查了一下。

  1. 所有路径都是用bash find命令制作的,所以没问题。
  2. 路径名称不包含任何古怪的字符。
  3. 删除.strip('\n')不会改变任何东西。
  4. 我使用的是Python 2.7.10。
python python-2.7 dictionary
1个回答
2
投票

使用os.path模块处理目录。假设一个文件有一行/path/to/file.ext,下面的代码

import os

with open('test.txt') as f:
    for line in f:
        line = line.strip()
        print(os.path.dirname(line))
        print(os.path.basename(line))

输出

/path/to
file.ext

现在,正如@Willem Van Onsem在评论中解释的那样,使用os.path.dirname作为密钥将覆盖同一目录中文件的先前路径。要解决此问题,您需要使用列表作为值:

import os
from collections import defaultdict

d = defaultdict(list)

with open('test.txt') as f:
    for line in f:
        line = line.strip()
        d[os.path.dirname(line)].append(os.path.basename(line))

现在考虑:

/path/to/file1.ext
/path/to/file2.ext
/path/to/file3.ext
/another/path/to/file4.ext

运行上面的代码后,print(d)将输出

defaultdict(<class 'list'>, {'/path/to': ['file1.ext', 'file2.ext', 'file3.ext'],
                             '/another/path/to': ['file4.ext']})
© www.soinside.com 2019 - 2024. All rights reserved.