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