使用PyGithub上传文件至GitHub指定子目录遇阻求助
解决GitHub仓库子目录文件上传问题
问题根源
- 路径格式不兼容:你使用了Windows风格的反斜杠
\\作为路径分隔符,而GitHub API要求使用正斜杠/,且路径不能以斜杠开头。 - 图片文件处理缺失:图片属于二进制文件,必须经过Base64编码后才能作为Git blob内容上传,你之前的代码注释掉了这部分逻辑,导致图片数据无法正确传递。
具体修改方案
1. 修正路径格式
将file_names中的反斜杠替换为正斜杠,符合GitHub API的路径规范:
file_names = [ f'pages/{fn}.html', f'images/{phot}' ]
2. 完善文件读取与编码逻辑
修改循环中的文件读取代码,分别处理HTML文本文件和图片二进制文件:
element_list = list() for i, entry in enumerate(file_list): if entry.endswith('.html'): # 读取文本类型的HTML文件 with open(entry, 'r', encoding="utf-8") as input_file: data = input_file.read() elif entry.endswith(('.png', '.jpg', '.webp')): # 读取二进制图片并转Base64编码(需解码为字符串) with open(entry, 'rb') as input_file: data = base64.b64encode(input_file.read()).decode('utf-8') else: # 跳过不支持的文件类型 continue element = InputGitTreeElement(file_names[i], '100644', 'blob', data) element_list.append(element)
3. 补充临时文件清理(可选)
你当前只删除了生成的HTML临时文件,建议在上传完成后同步清理临时图片文件,避免本地残留:
os.remove(f"{fn}.html") os.remove(phot) # 确保phot是本地临时文件路径
修改后的完整load函数示例
def load(): try: fn = datetime.now().strftime("%Y-%m-%d") artic = Text.get('1.0', 'end') artic = artic.replace("\n", "<br>") artna = Name.get() regl = Regist.get() dienl = Dienas.get() whfi = """here was html page, it works just fine""" # 生成临时HTML文件 html_temp_path = f'{fn}.html' with open(html_temp_path, 'wt', encoding="utf-8") as f: f.write(whfi) phots = photo() if not phots: messagebox.showwarning("警告", "未选择图片文件") os.remove(html_temp_path) return phot = os.path.basename(phots) # 复制图片到临时路径(避免修改原文件) import shutil phot_temp_path = phot shutil.copy(phots, phot_temp_path) file_list = [html_temp_path, phot_temp_path] file_names = [ f'pages/{fn}.html', f'images/{phot}' ] master_ref = repo.get_git_ref('heads/main') master_sha = master_ref.object.sha base_tree = repo.get_git_tree(master_sha) element_list = list() for i, entry in enumerate(file_list): if entry.endswith('.html'): with open(entry, 'r', encoding="utf-8") as input_file: data = input_file.read() elif entry.endswith(('.png', '.jpg', '.webp')): with open(entry, 'rb') as input_file: data = base64.b64encode(input_file.read()).decode('utf-8') else: continue element = InputGitTreeElement(file_names[i], '100644', 'blob', data) element_list.append(element) tree = repo.create_git_tree(element_list, base_tree) parent = repo.get_git_commit(master_sha) commit = repo.create_git_commit(commit_message, tree, [parent]) master_ref.edit(commit.sha) # 清理临时文件 os.remove(html_temp_path) os.remove(phot_temp_path) messagebox.showinfo("成功", "文件上传完成") except Exception as e: messagebox.showerror("错误", f"上传失败:{str(e)}") # 异常时也要清理临时文件 if 'html_temp_path' in locals() and os.path.exists(html_temp_path): os.remove(html_temp_path) if 'phot_temp_path' in locals() and os.path.exists(phot_temp_path): os.remove(phot_temp_path)
内容的提问来源于stack exchange,提问作者Chur-Ka Han
相关产品推荐
相关产品推荐

