1

#The above code should pull file form github and past in my local directory "C:\Users\HP"..not working as expected,the rpository is public'

Below is code:

import requests

def pull_files(repo_url, directory, filename):
  """
     Pulls a specific file from the specified GitHub repository into the specified directory.

  Args:
    repo_url: The URL of the GitHub repository.
    directory: The directory to store the files in.
    filename: The name of the file to pull.
  """
  response = requests.get(repo_url + "/blob/main/" + filename)
  if response.status_code != 200:
    raise Exception("Failed to get file.")

  with open(os.path.join(directory, filename), "wb") as f:
    f.write(response.content)

 if __name__ == "__main__":
  repo_url = "https://github.com/Hackerash008/Test/blob/main/.github/workflows/bard.py"
  directory = "C:\\Users\\HP"
  filename = "bard.py"
  pull_files(repo_url, directory, filename)
Cow
  • 2,543
  • 4
  • 13
  • 25

1 Answers1

1

You have your paths wrong. Your repo_url just needs to have repo, not the whole path. You add the rest later, and you were doing that incorrectly as well.

import os
import requests

def pull_files(repo_url, directory, filename):
    """
        Pulls a specific file from the specified GitHub repository into the specified directory.

    Args:
        repo_url: The URL of the GitHub repository.
        directory: The directory to store the files in.
        filename: The name of the file to pull.
    """
    response = requests.get(repo_url + "/blob/main/.github/workflows/" + filename)
    if response.status_code != 200:
        raise Exception("Failed to get file.")

    with open(os.path.join(directory, filename), "wb") as f:
        f.write(response.content)

if __name__ == "__main__":
    repo_url = "https://github.com/Hackerash008/Test"
    directory = "."
    filename = "bard.py"
    pull_files(repo_url, directory, filename)
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
  • Note that I don't actually GET the file with this. What I get is a JSON block telling me I haven't logged in. – Tim Roberts Jul 27 '23 at 05:28
  • HI Tim,Thanks for your reply....It is working,My objective is our development team will upload a new code in repo..whenever new code is uploaded have to pull that file to our third part tool – Enthusaistic Jul 27 '23 at 07:39
  • Please read the link in shaik moeed's comment. There is a GitPython package that is designed specifically for interacting with git. That would be a better choice then the web scrape hacking you are doing now. – Tim Roberts Jul 27 '23 at 19:06