您可能应该使用“列表理解”。这是一个如何做到这一点的示例:
lst_names = [os.path.join(full_subdir_name, n) for n in os.listdir(full_subdir_name)]
因此,您将构建完整的namelist
类似这样的东西。首先,您应该设置一个名称列表。
# example using Windwows filenames
# note that we use "raw strings" with r'' so the backslash will not be weird
lst_names = [r'C:\Users\steveha\Desktop', r'C:\Users\steveha\Documents', r'C:\Users\steveha\Music']
# example using Mac or Linux filenames
lst_names = ['/home/steveha/Desktop', '/home/steveha/Documents', '/home/steveha/Music'
lst_names
设置好姓名后,构建完整的namelist
:
namelist = {}
for full_subdir_name in lst_names:
namelist[full_subdir_name] = [os.path.join(full_subdir_name, n) for n in os.listdir(full_subdir_name)]
就我个人而言,我认为使用更短的变量名比阅读更容易full_subdir_name
:
namelist = {}
for f in lst_names:
namelist[f] = [os.path.join(f, n) for n in os.listdir(f)]