DEV Community

Developer213
Developer213

Posted on

Add files to GitHub


.py

import requests

# GitHub repository details
base_url = ''
repo_owner = ''
repo_name = ''
branch_name = ''
file_path = '/'

# Your personal access token
personal_access_token = 'your_personal_access_token'

# Path of the file you want to upload
local_file_path = 'path/to/your/file.ext'  # Replace with your file path

# Read file content
with open(local_file_path, 'rb') as file:
    encoded_content = file.read().decode('utf-8')

# Construct the API endpoint
api_url = f'{base_url}/repos/{repo_owner}/{repo_name}/contents/{file_path}'

# Commit data
commit_data = {
    "message": "Uploading file from Jupyter Notebook",
    "content": encoded_content,
    "branch": branch_name
}

# Headers with the personal access token
headers = {
    'Authorization': f'token {personal_access_token}',
    'Accept': 'application/vnd.github.v3+json'
}

# Make the API request
response = requests.put(api_url, json=commit_data, headers=headers)

# Print response
print(response.json())
Enter fullscreen mode Exit fullscreen mode

Top comments (0)