0% found this document useful (0 votes)
4 views2 pages

Download Files in Various Formats

Uploaded by

relaxxx34
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views2 pages

Download Files in Various Formats

Uploaded by

relaxxx34
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

import requests

import os
from [Link] import urlparse

def download_file(url, save_format):


try:
# Send GET request to the URL
response = [Link](url)
response.raise_for_status() # Raise an exception for bad status codes

# Get filename from URL or generate default name


parsed_url = urlparse(url)
filename = [Link](parsed_url.path)
if not filename:
filename = f"downloaded_file.{save_format}"

# Ensure correct extension


if not [Link](f".{save_format}"):
filename = f"{[Link](filename)[0]}.{save_format}"

# Save file locally


with open(filename, 'wb') as file:
[Link]([Link])

print(f"File saved as: {[Link](filename)}")


return [Link](filename)

except [Link] as e:
print(f"Error downloading file: {e}")
return None
except Exception as e:
print(f"Error saving file: {e}")
return None

def main():
url = input("Enter the URL to download: ").strip()
if not url:
print("No URL provided.")
return

print("Select save format:")


print("1. CSV")
print("2. TXT")
print("3. PDF")

choice = input("Enter choice (1/2/3): ").strip()


format_map = {'1': 'csv', '2': 'txt', '3': 'pdf'}

if choice not in format_map:


print("Invalid choice. Defaulting to TXT format.")
choice = '2'

save_format = format_map[choice]
saved_path = download_file(url, save_format)

if saved_path:
print(f"File successfully downloaded and saved to: {saved_path}")
else:
print("Failed to download/save the file.")
if __name__ == "__main__":
main()

You might also like