【问题标题】:Alphabetically enumerate files in directories with attributes按字母顺序枚举具有属性的目录中的文件
【发布时间】:2019-05-27 20:02:20
【问题描述】:

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

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

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))

现在的问题是,在我的 content 列表中有一个“.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                                    

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

【问题讨论】:

    标签: python python-3.x github enumeration pygithub


    【解决方案1】:

    您应该在迭代之前创建文件名列表并对其进行排序

    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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-12
      • 1970-01-01
      • 2014-07-11
      • 2018-06-11
      • 2017-06-11
      • 2015-04-14
      • 1970-01-01
      相关资源
      最近更新 更多