Search code examples
pythonpython-3.xgithubenumerationpygithub

Alphabetically enumerate files in directories with attributes


I'm trying to enumerate in alphabetical order two lists of files based on different directories.

One list is the files in my directory using the following code:

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

which will return

file_b.py
file_c.py
file_d.txt

Issue being one list is coming from a github repository

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

Which will return

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

For now I'm using zip to do as follows:

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

Now issue is that in my content list has a ".name" attribute while my os dirlist doesn't

So what I'd like to get is:

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

However what I get is:

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

I'm not sure how I would go to fix this? Is there anyway to sort and enumerate two lists with attributes while keeping the number consistent? And at the same time order it alphabetically?


Solution

  • You should create and sort your list of file names before iteration

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