how to download a file locally using python
- User
how to download a file locally using python
- Assistant
You can use the
requestslibrary in Python to download a file from a URL and save it locally. Here's an example code snippet:pythonimport requests url = 'http://example.com/file.txt' response = requests.get(url) if response.status_code == 200: with open('file.txt', 'wb') as file: file.write(response.content) print('File downloaded successfully') else: print('Failed to download file')In this code snippet, we first import the
requestslibrary. We then define the URL of the file we want to download. We make a GET request usingrequests.get(url)and check if the response status code is 200 (indicating a successful response). If it is, we open a new file in binary write mode and write the content of the response to it. Finally, we print a message indicating whether the file was downloaded successfully or not. - User
no, my python app is running on browser and when i click on some button , i want to download a file locally in my system
- Assistant
If you want to trigger a file download in the browser when a button is clicked in your web application, you can use JavaScript along with Python's Flask framework to serve the file. Here's an example code snippet to achieve this:
- Python Flask code:
pythonfrom flask import Flask, send_file app = Flask(__name) @app.route('/download') def download_file(): file_path = 'path_to_your_file/file.txt' return send_file(file_path, as_attachment=True) if __name__ == '__main__': app.run()- HTML code:
html