Advertisement
Guest User

Download Google Sheets as CSV + Overwrite file

a guest
Apr 17th, 2025
34
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.01 KB | Source Code | 0 0
  1. import gspread
  2. from oauth2client.service_account import ServiceAccountCredentials
  3. import csv
  4. import os
  5. from pathlib import Path
  6. from datetime import datetime
  7.  
  8. # ===== CONFIGURATION =====
  9. CREDENTIALS_FILE = "credentials.json"
  10. SPREADSHEET_ID = "Put in here your spreadsheet ID"
  11. GAME_FOLDER = r"Put in here the output folder"
  12. CSV_NAME = "name of the output file.csv"
  13. # =========================
  14.  
  15. def main():
  16.     try:
  17.         # 1. Authentication
  18.         scope = ["https://www.googleapis.com/auth/spreadsheets"]
  19.         creds = ServiceAccountCredentials.from_json_keyfile_name(CREDENTIALS_FILE, scope)
  20.         client = gspread.authorize(creds)
  21.        
  22.         print("✅ Successfully authenticated with Google Sheets API")
  23.  
  24.         # 2. Access spreadsheet
  25.         spreadsheet = client.open_by_key(SPREADSHEET_ID)
  26.         worksheet = spreadsheet.get_worksheet(0)
  27.        
  28.         print(f"📄 Accessing: '{spreadsheet.title}' > '{worksheet.title}'")
  29.  
  30.         # 3. Prepare output
  31.         output_path = Path(GAME_FOLDER) / CSV_NAME
  32.         os.makedirs(GAME_FOLDER, exist_ok=True)
  33.  
  34.         # 4. Export with proper CSV formatting
  35.         with open(output_path, 'w', newline='', encoding='utf-8') as f:
  36.             writer = csv.writer(f,
  37.                               delimiter=',',
  38.                               quotechar='"',
  39.                               quoting=csv.QUOTE_MINIMAL)
  40.             writer.writerows(worksheet.get_all_values())
  41.        
  42.         # Success message
  43.         current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  44.         row_count = len(worksheet.get_all_values())
  45.         print(f"💾 Exported {row_count} rows to: {output_path}")
  46.         print(f"⏱️ {current_time} | Format: Standard CSV (quoted fields)")
  47.  
  48.     except Exception as e:
  49.         print(f"❌ Error: {str(e)}")
  50.         print("\nTROUBLESHOOTING:")
  51.         print(f"1. Check sharing permissions for: {creds.service_account_email}")
  52.         print("2. Verify worksheet contains data")
  53.  
  54. if __name__ == "__main__":
  55.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement