PyGithub-如何在仓库中获取子文件夹的内容

时间:2018-11-28 20:43:43

标签: python recursion pygithub

我正在尝试在给定的github存储库中获取子文件夹“ github”的内容。这似乎不起作用。

repo = g.get_repo("PyGithub/PyGithub")
contents = repo.get_contents("github")
while len(contents) > 1:
    file_content = contents.pop(0)
    if file_content.type == "dir":
        contents.extend(repo.get_contents(file_content.path))
    else:
        print(file_content)

3 个答案:

答案 0 :(得分:0)

代码段可以正常工作:

enter image description here

您遇到什么错误?

答案 1 :(得分:0)

对以上答案的小修正。使用 len(contents)> 0 ,否则您将丢失一个文件

from github import Github
g = Github()
repo = g.get_repo("PyGithub/PyGithub")
contents = repo.get_contents("github")
while len(contents)>0:
  file_content = contents.pop(0)
  if file_content.type=='dir':
    contents.extend(repo.get_contents(file_content.path))
  else :
    print(file_content)

答案 2 :(得分:0)

from github import Github

access_token = "[access_tokey]"

hub = Github(access_token) # Github(user, pass)

# Displaying all the existing Repositories and files
for repo in hub.get_user().get_repos():
    # Displaying repo name
    print("Repository [{}]".format(repo.name))
    print("_" * 50)
    # Displaying Contents
    print("[Contents]")
    count = 1
    for content in repo.get_contents(""):
        print("{}. {} [{}]".format(count, content.path, content.type))
        if content.type == 'dir':
            new_count = 1
            # Displaying contents of sub-director
            for sub_content in repo.get_contents(content.path):
                print("    {}. {} [{}]".format(new_count, sub_content.path, sub_content.type))
                new_count += 1
                # Displaying contents of sub directory of sub directory
                if sub_content.type == 'dir':
                    another_count = 1
                    for datain in repo.get_contents(sub_content.path):
                        print("        {}. {} [{}]".format(another_count, datain.path, datain.type))
                        another_count += 1

        count += 1
    print("-" * 50)