溫馨提示×

python怎么讀取data數(shù)據(jù)

小億
146
2023-10-31 16:33:34
欄目: 編程語言

在Python中,有多種方法可以讀取數(shù)據(jù)。以下是一些常見的方法:

  1. 使用open函數(shù)打開文件,然后使用read方法讀取文件中的數(shù)據(jù):
file = open("data.txt", "r")  # 打開文件
data = file.read()  # 讀取文件中的數(shù)據(jù)
file.close()  # 關(guān)閉文件
  1. 使用with語句結(jié)合open函數(shù),可以自動關(guān)閉文件:
with open("data.txt", "r") as file:
    data = file.read()  # 讀取文件中的數(shù)據(jù)
  1. 讀取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ù)
  1. 讀取JSON格式的數(shù)據(jù),可以使用json模塊:
import json

with open("data.json", "r") as file:
    data = json.load(file)  # 加載JSON數(shù)據(jù)

這些方法可以根據(jù)不同的數(shù)據(jù)格式和需求進行選擇和調(diào)整。

0