pip install google-api-python-client google-auth google-auth-oauthlib google-auth-httplib2요즘 하는 프로젝트에서 배운 3가지 다운로드 방법을 정리한다.
1. requests 로 다운로드
2. gdown을 이용해서 다운로드
3. Google drive api를 이용해서 다운로드
나는 mp3파일을 다운로드 해야했으므로, 파일이 중간에 깨지면 (스트림이 중단되면) 온전한 파일로 인식하지 못해 문제가 생겼다. 그래서 1->2>을 거쳐 3번 방법을 시도해보기에 이르렀다.
물론 wget 도 시도했지만 역시나 실패..
1. requests
먼저 requests로 다운로드 하는 방법이다. 필자는 mp3파일이라서 사용하지 못했지만 일반적인 파일에는 적용가능하리라.
import requests
def download_audio(url, filename="temp_audio.mp3"):
    """Google Drive에서 MP3 파일 다운로드 (Windows 호환)"""
    try:
        response = requests.get(url, stream=True)
        if response.status_code == 200:
            with open(filename, "wb") as f:
                for chunk in response.iter_content(chunk_size=8192):
                    f.write(chunk)
            logging.info(f"✅ MP3 다운로드 완료: {filename}")
            return filename
        else:
            logging.error(f"❌ MP3 다운로드 실패 (HTTP {response.status_code})")
            return None
    except Exception as e:
        logging.error(f"❌ 다운로드 오류: {e}")
        return None
2. gdown
import gdown 
def download_audio(url, filename="temp_audio.mp3"):
    """Google Drive에서 MP3 파일 다운로드 (`gdown` 사용)"""
    try:
        file_id = extract_drive_file_id(url)
        if not file_id:
            logging.error(f"❌ 올바르지 않은 Google Drive 링크: {url}")
            return None
        drive_download_url = f"https://drive.google.com/uc?id={file_id}"
        gdown.download(drive_download_url, filename, quiet=False)
이하는 mp3의 경우 파일 유효성 검사코드
if not filename.endswith(".mp3") or os.path.getsize(filename) < 1000:
    logging.error(f"❌ MP3 파일이 손상되었거나 올바르지 않음: {filename}")
    return None
3. Google Drive API 사용
from google.oauth2 import service_account
SERVICE_ACCOUNT_FILE = "setting/credentials.json"
SCOPES = [
    "https://www.googleapis.com/auth/spreadsheets",  # Google Sheets API 권한
    "https://www.googleapis.com/auth/drive"         # Google Drive API 권한 
]
creds = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
drive_service = build("drive", "v3", credentials=creds)
def download_audio_from_drive(file_id, filename="temp_audio.mp3"):
    """Google Drive에서 MP3 파일 다운로드 (Google Drive API 사용)"""
    try:
        request = drive_service.files().get_media(fileId=file_id)
        with open(filename, "wb") as f:
            f.write(request.execute())
        # ✅ 다운로드된 파일이 실제 MP3인지 확인
        if not filename.endswith(".mp3") or os.path.getsize(filename) < 1000:  # 1KB 이하 파일은 손상 가능성 있음
            logging.error(f"❌ MP3 파일이 손상되었거나 올바르지 않음: {filename}")
            return None
        logging.info(f"✅ MP3 다운로드 완료: {filename}")
        return filename
위 코드를 실행하려면 , pip는 최신버전으로 해야함 주의
pip install google-api-python-client google-auth google-auth-oauthlib google-auth-httplib2
728x90
    
    
  '개발로그 > Python' 카테고리의 다른 글
| 구글드라이브에서 API로 파일 탐색을 할 때, 어떻게 하는게 더 효율적일까? feat ChatGPT (0) | 2025.03.11 | 
|---|---|
| Pygame에서 나오는 모든 소리를 하나의 파일(wav)로 저장하는 방법 (0) | 2025.03.10 | 
| threading.Event() 객체의 활용 예제 및 백그라운드 실행 정리 (0) | 2025.03.09 | 
| FFmpeg 다운로드 및 설치 (0) | 2025.03.08 | 
| Vscode or Jupyter notebook conda 환경에서 실행되도록 설정하기 (0) | 2025.03.06 | 
| 파이썬을 활용하는 머신러닝 딥러닝 차이 그리고 ai란? 한방에 정리하기 (2) | 2022.12.20 | 
| 책으로 코딩 독학하시는 분, 저만의 독서법을 가르쳐드립니다. (0) | 2022.11.25 | 
| 파이썬 독학 책, 실패 없이 고르는 방법 (2) | 2022.11.24 | 
 
										
									 
										
									 
										
									
댓글