使用 python 下載文件并打開文件包含以下步驟:導入請求庫。使用 requests.get() 方法發送 http get 請求。檢查 http 狀態代碼(200 表示成功)。將下載的文件內容寫入本地文件。使用 open() 函數打開下載的文件。
使用 Python 下載文件并打開
下載文件并使用 Python 打開文件相對簡單。以下是完成此任務的分步指南:
1. 導入必要的庫
首先,你需要導入 requests
庫,它用于發送 HTTP 請求并下載文件。
import requests
關注:愛掏網
2. 發送 HTTP 請求
使用 requests.get()
方法發送 HTTP GET 請求以下載文件。該方法接收文件 URL 作為參數。
url = 'https://example.com/file.txt' response = requests.get(url)
關注:愛掏網
3. 檢查狀態代碼
HTTP 狀態代碼指示請求是否成功。200 表示成功下載。
if response.status_code == 200: print('文件下載成功') else: print('文件下載失敗')
關注:愛掏網
4. 寫入文件
將下載的文件的內容寫入本地文件中。
with open('file.txt', 'wb') as f: f.write(response.content)
關注:愛掏網
5. 打開文件
使用 open()
函數打開已下載的文件。
with open('file.txt', 'r') as f: content = f.read()
關注:愛掏網
實戰案例:下載文本文件
import requests url = 'https://raw.githubusercontent.com/learnpython/sample-code/master/exercises/file.txt' response = requests.get(url) if response.status_code == 200: with open('downloaded_file.txt', 'wb') as f: f.write(response.content) with open('downloaded_file.txt', 'r') as f: content = f.read() print(content)
關注:愛掏網
這段代碼將從指定 URL 下載文本文件,將其寫入名為 downloaded_file.txt
的本地文件,并打印其內容。
以上就是Python下載完成后如何打開的詳細內容,更多請關注愛掏網 - it200.com其它相關文章!
聲明:所有內容來自互聯網搜索結果,不保證100%準確性,僅供參考。如若本站內容侵犯了原著者的合法權益,可聯系我們進行處理。