基于字符串的Python文件处理

2024-09-30 16:39:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有大量的.json文件,这些文件是按ID排序的:例如tramgj128f421487e.json是按第3到第5个字母排序的,所以这将在目录:../A/M/G/tramgj128f421487e.json中

我的问题是:如何根据给定的ID打开正确的文件? 每个目录中都有A-Z/A-Z/A-Z/文件


Tags: 文件目录idjson排序字母tramgj128f421487e
1条回答
网友
1楼 · 发布于 2024-09-30 16:39:20

你就不能通过分裂字符串来解决这个问题吗

base = "/" #  Your base directory here
json_file = 'TRAMGJJ128F421487E.json'  # Input ID
folder_one, folder_two, folder_three = json_file[2:5]
filename = os.path.join(base,
                        folder_one,
                        folder_two,
                        folder_three,
                        json_file)

在Python3.5中,您只需动态地解包一个iterable:

base = "/" #  Your base directory here
json_file = 'TRAMGJJ128F421487E.json'  # Input ID
os.path.join(base, *json_file[2:5], json_file)

相关问题 更多 >