如何用PyGithub读取GitHub仓库CSV文件并处理ContentFile类型
解决方法
你当前的问题在于repo.get_contents()返回的是ContentFile对象,不是本地文件路径,所以不能直接用open()打开。要获取CSV内容,调用ContentFile的decoded_content属性即可,它会自动解码文件的base64编码内容。
基础实现代码
from github import Github g = Github(token) repo = g.get_repo("user/example") contents = repo.get_contents("h.csv") # 解码内容并转为字符串,按行分割处理 csv_content = contents.decoded_content.decode("utf-8") lines = csv_content.splitlines() last_line = lines[-1] last_id_csv = last_line.split(",")[0] print(last_id_csv) # 输出示例中的4
更健壮的CSV处理(应对含逗号的字段)
如果CSV字段中可能包含逗号(比如text字段值为"hi, there"),直接用split(",")会出错,推荐用Python内置的csv模块处理:
from github import Github import csv from io import StringIO g = Github(token) repo = g.get_repo("user/example") contents = repo.get_contents("h.csv") # 将解码后的内容转为可被csv模块读取的文件对象 csv_file = StringIO(contents.decoded_content.decode("utf-8")) reader = csv.DictReader(csv_file) # 获取最后一行数据 rows = list(reader) last_row = rows[-1] last_id_csv = last_row["id"] print(last_id_csv) # 输出示例中的4
内容的提问来源于stack exchange,提问作者carlosnev
相关产品推荐
相关产品推荐

