You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python调用GitHub API无法正确创建目录的问题排查

问题分析与修复方案

原代码存在的核心问题

  1. 目录层级管理错误:current_dir 列表会无差别追加所有条目(文件和目录),导致路径中混入文件名作为目录,比如生成 dir2/file1/file1 这种错误路径。
  2. 未处理同级目录切换:当从 dir2 切换到同级的 dir3 时,没有将 current_dir 回退到父目录层级,导致 dir3 被错误嵌套在 dir2 下。
  3. 目录创建方式错误:GitHub API 不允许直接创建空目录,原代码试图将目录名作为文件创建(比如 dir1),实际生成的是文件而非目录。
  4. 根目录处理不当:根目录未被识别为目录结构,而是被当作普通文件创建。

修复方案

关键改进点

  1. 新增 parse_line 函数:解析每行的层级深度、名称和是否为目录,通过标记符(├──/└──)的缩进位置计算层级。
  2. 正确管理 current_dir:根据当前条目层级截断 current_dir 到父目录层级,再添加新目录,确保层级结构正确。
  3. 通过 .gitkeep 创建目录:GitHub 需要目录下存在文件才能创建目录,因此在每个目录下生成空的 .gitkeep 文件。
  4. 重构 create_file 函数:直接接收完整路径,避免路径拼接错误。

完整修复代码

from github import Github
import re

def create_repository(username, token, repository_name):
    g = Github(username, token)
    repo = g.get_user().create_repo(repository_name)
    print(f"Successfully created repository: {repository_name}")
    return repo

def parse_line(line):
    line = line.strip()
    is_directory = line.endswith('/')
    
    if line.startswith(('├──', '└──')):
        name = line[3:].strip().rstrip('/')
        name = re.sub('[^a-zA-Z0-9.]', '', name)
        marker_start = line.find('├──') if '├──' in line else line.find('└──')
        depth = (marker_start // 4) + 1
    else:
        name = line.rstrip('/')
        name = re.sub('[^a-zA-Z0-9.]', '', name)
        depth = 0
    
    return depth, name, is_directory

def create_file(repo, path):
    try:
        repo.create_file(path, 'Initial commit', '')
        print(f"Successfully created file: {path}")
    except Exception as e:
        print(f"Error creating file {path}: {e}")

def create_file_structure(repo, file_structure):
    lines = file_structure.strip().split('\n')
    current_dir = []
    
    for line in lines:
        depth, name, is_directory = parse_line(line)
        
        if is_directory:
            parent_path = current_dir[:depth]
            current_dir = parent_path + [name]
            dir_path = '/'.join(current_dir + ['.gitkeep'])
            create_file(repo, dir_path)
        else:
            parent_path = current_dir[:depth]
            file_path = '/'.join(parent_path + [name])
            create_file(repo, file_path)
    
    print('Successfully created file structure')

def main():
    username = input('Enter your GitHub username: ')
    token = input('Enter your GitHub personal access token: ')
    repository_name = input('Enter the repository name: ')
    repo = create_repository(username, token, repository_name)
    
    print("Paste your file structure (press enter twice to finish):")
    lines = []
    while True:
        line = input()
        if line:
            lines.append(line)
        else:
            break
    file_structure = '\n'.join(lines)
    
    create_file_structure(repo, file_structure)

if __name__ == '__main__':
    main()

修复效果

运行修复后的代码,输入预期的文件结构,将生成正确的目录层级:

  • dir1/(包含 .gitkeep)
    • dir2/(包含 .gitkeep)
      • file1
      • file2
    • dir3/(包含 .gitkeep)
      • file3
      • file4
      • dir4/(包含 .gitkeep)
        • file5

内容的提问来源于stack exchange,提问作者OrbitalMartian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 17:15:10