如何使用 python 从 git 存储库获取特定文件版本

How to get specific file version from git repository using python

我有一个本地 git 存储库,我正在尝试找到一种方法将我的 xlsx 文件的特定版本放入我的 Python 代码中,以便我可以使用 [=23] 处理它=].

我找到了 gitpython 库;但我不确定如何正确使用它。

repo = Repo(path_to_repo)
commit = repo.commit(sha)
targetfile = commit.tree / 'dataset.xlsx'

我不知道接下来要做什么。 我尝试使用路径将它加载到 pandas;但是,当然,它只会加载我的最后一个版本。

如何将以前版本的 xlsx 加载到 pandas?

当你请求 commit.tree / 'dataset.xlsx' 时,你得到一个 git.Blob 对象:

>>> targetfile
<git.Blob "3137d9443f54325b8ad8a263b13053fee47fbff2">

如果要读取对象的内容,可以使用data_stream方法提取内容,其中returns一个file-like对象:

>>> data = targetfile.data_stream.read()

或者你可以使用stream_data方法(别看我,我没给它们起名字),它把数据写入一个file-like对象:

>>> import io
>>> buf = io.BytesIO()
>>> targetfile.stream_data(buf)
<git.Blob "3137d9443f54325b8ad8a263b13053fee47fbff2">
>>> buf.getvalue()
b'The contents of the file...'