我有带路径的文本文件,例如:
/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)
检查了一下。
find
命令制作的,所以没问题。.strip('\n')
不会改变任何东西。使用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']})