是否有可能一次循环列表中的所有元素?



想要读取文件夹内容并将其转换为字典。下面是我的基本方法。

代码片段:

import os
b_path = "/home/work/assignments/chapters"
output = {}

for path, subdirs, files in os.walk(b_path):
for name in subdirs:
tmp = os.path.join(path, name)
tmp_arr = [i for i in os.listdir(tmp)]
for i, v in enemurate(tmp_arr):
output[name] = [os.path.join(tmp, v)]
output[name].append(os.path.join(tmp, <not sure how to achieve this> ))]
print(output)

subdirs打印文件夹名称-countries, social, algebra, functions等。

subdir(文件夹)下包含2个文件,Yaml文件;. Zip或tar.gz文件

tmp_arr's输出

['func.yaml', 'sensor.zip']
['packets.tar.gz', 'check.yaml']
['mt101.tar.gz', 'provider.yaml']
and so on.

我想让我的字典看起来像:

{
"countries": [
"/home/work/assignments/chapters/countries/func.yaml",
"/home/work/assignments/chapters/countries/sensor.zip"
],
"social": [
"/home/work/assignments/chapters/social/check.yaml",
"/home/work/assignments/chapters/social/packets.tar.gz"
],
and so on
}

我有一个这样的文件夹结构:

Sample
│
└───folderA
│   │   A1.txt
│   │   A2.txt
│  
└───folderB
│   B1.txt
│   B2.txt

import os
b_path = "Sample"
output = {}
for path, subdirs, files in os.walk(b_path):
for name in files:
folder = os.path.basename(path)
if output.get(folder) is None:
output[folder] = [name]
else:
output[folder].append(name)
print(output)

{'folderA': ['A1.txt', 'A2.txt'], 'folderB': ['B1.txt', 'B2.txt']}

这样做怎么样:-

import glob
D = {}
for _r in glob.glob('/home/work/assignments/chapters/*/*'):
t = _r.split('/')
if (d := t[-2]) in D:
D[d].append(t[-1])
else:
D[d] = [t[-1]]
print(D)

试试这个

import os
def list_files(dir):
for root, dirs, files in os.walk(dir):
names=[]
for name in files:
print(name)
r.append(os.path.join(root, name))
names.append(os.path.join(root, name))
output[root.split('/')[-1]]=names
return output

喜欢这个吗?

from os import sep
from glob import glob
from pprint import pprint
pprint({d.split(sep)[1] : [f for f in  glob(d +'/*.*')] for d in glob('/home/work/assignments/chapters/*/')})

sep为跨平台支持,pprint为"pretty-print"d为目录,f为文件。

相关内容

  • 没有找到相关文章

最新更新