使用 python 下載文件并打開(kāi)文件包含以下步驟:導(dǎo)入請(qǐng)求庫(kù)。使用 requests.get() 方法發(fā)送 http get 請(qǐng)求。檢查 http 狀態(tài)代碼(200 表示成功)。將下載的文件內(nèi)容寫(xiě)入本地文件。使用 open() 函數(shù)打開(kāi)下載的文件。
使用 Python 下載文件并打開(kāi)
下載文件并使用 Python 打開(kāi)文件相對(duì)簡(jiǎn)單。以下是完成此任務(wù)的分步指南:
1. 導(dǎo)入必要的庫(kù)
首先,你需要導(dǎo)入 requests
庫(kù),它用于發(fā)送 HTTP 請(qǐng)求并下載文件。
import requests
2. 發(fā)送 HTTP 請(qǐng)求
使用 requests.get()
方法發(fā)送 HTTP GET 請(qǐng)求以下載文件。該方法接收文件 URL 作為參數(shù)。
url = 'https://example.com/file.txt' response = requests.get(url)
3. 檢查狀態(tài)代碼
HTTP 狀態(tài)代碼指示請(qǐng)求是否成功。200 表示成功下載。
if response.status_code == 200: print('文件下載成功') else: print('文件下載失敗')
4. 寫(xiě)入文件
將下載的文件的內(nèi)容寫(xiě)入本地文件中。
with open('file.txt', 'wb') as f: f.write(response.content)
5. 打開(kāi)文件
使用 open()
函數(shù)打開(kāi)已下載的文件。
with open('file.txt', 'r') as f: content = f.read()
實(shí)戰(zhàn)案例:下載文本文件
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 下載文本文件,將其寫(xiě)入名為 downloaded_file.txt
的本地文件,并打印其內(nèi)容。
以上就是Python下載完成后如何打開(kāi)的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注愛(ài)掏網(wǎng) - it200.com其它相關(guān)文章!