共計(jì) 489 個(gè)字符,預(yù)計(jì)需要花費(fèi) 2 分鐘才能閱讀完成。
在 Python 中,有多種方法可以讀取數(shù)據(jù)。以下是一些常見(jiàn)的方法:
- 使用 open 函數(shù)打開(kāi)文件,然后使用 read 方法讀取文件中的數(shù)據(jù):
file = open("data.txt", "r") # 打開(kāi)文件
data = file.read() # 讀取文件中的數(shù)據(jù)
file.close() # 關(guān)閉文件
- 使用 with 語(yǔ)句結(jié)合 open 函數(shù),可以自動(dòng)關(guān)閉文件:
with open("data.txt", "r") as file:
data = file.read() # 讀取文件中的數(shù)據(jù)
- 讀取 CSV 格式的數(shù)據(jù),可以使用 csv 模塊:
import csv
with open("data.csv", "r") as file:
csv_reader = csv.reader(file) # 創(chuàng)建 CSV 讀取器
for row in csv_reader:
print(row) # 打印每一行數(shù)據(jù)
- 讀取 JSON 格式的數(shù)據(jù),可以使用 json 模塊:
import json
with open("data.json", "r") as file:
data = json.load(file) # 加載 JSON 數(shù)據(jù)
這些方法可以根據(jù)不同的數(shù)據(jù)格式和需求進(jìn)行選擇和調(diào)整。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完