首页 > 解决方案 > 按字母顺序枚举具有属性的目录中的文件

问题描述

我正在尝试按字母顺序枚举两个基于不同目录的文件列表。

一个列表是使用以下代码在我的目录中的文件:

import os
file_list = os.listdir('./')
for x in file_list:
    print(x)

这将返回

file_b.py
file_c.py
file_d.txt

问题是一个列表来自 github 存储库

from github import Github
g = Github("token")
repo = g.get_repo("Name/Repo")
for content in repo.get_contents("files"):
    print(content.name)

哪个会回来

File_a.py
File_b.c
File_c.txt
File_d.py

现在我正在使用 zip 执行以下操作:

from github import Github
import os
g = Github("token")
repo = g.get_repo("Name/Repo")
content = repo.get_contents("files")

for elt, (x, y) in enumerate(zip(content, os.listdir('./'))):
    if x.name.endswith('.py'):
        print('[{}] {}'.center(79).format(str(elt), x.name))
    if y.endswith('.py'):
        print('[{}] {}'.center(79).format(str(elt), y))

现在的问题是我的内容列表中有一个“.name”属性,而我的 os dirlist 没有

所以我想得到的是:

                                    [0] file_a.py                                    
                                    [1] file_b.py                                    
                                    [2] file_c.py   
                                    [3] file_d.py                                 

但是我得到的是:

                                    [0] file_a.py                                    
                                    [0] file_b.py                                    
                                    [1] file_d.py                                    
                                    [1] file_c.py                                    

我不确定我将如何解决这个问题?无论如何要对两个具有属性的列表进行排序和枚举,同时保持数字一致?同时按字母顺序排列?

标签: pythonpython-3.xgithubenumerationpygithub

解决方案


您应该在迭代之前创建和排序文件名列表

import os
g = Github("token")
repo = g.get_repo("Name/Repo")
file_names = repo.get_contents("files")
file_names.extend([f.name for f in os.listdir('./')])

for index, file_name in enumerate(sorted(file_names)):
    if file_name.endswith('.py'):
        print('[{}] {}'.center(79).format(str(index), file_name))

推荐阅读