要從 CSV 檔案讀取數據,請使用 Python CSV 函式庫。以下是範例:
import csv # Open the CSV file for reading with open("test.csv", "rt") as f: # Create a CSV reader object reader = csv.reader(f, delimiter=",", quotechar='"') # Iterate over the rows in the CSV file for row in reader: print(row)
要將資料寫入CSV 文件,也可以使用Python CSV 函式庫:
import csv # Create a list of data to write to the CSV file data = [ (1, "A towel", 1.0), (42, " it says, ", 2.0), (1337, "is about the most ", -1), (0, "massively useful thing ", 123), (-2, "an interstellar hitchhiker can have.", 3), ] # Open the CSV file for writing with open("test.csv", "wt") as f: # Create a CSV writer object writer = csv.writer(f, delimiter=",", quotechar='"') # Write the data to the CSV file writer.writerows(data)
使用CSV時檔:
以下是範例程式碼的輸出:
1,"A towel,",1.0 42," it says, ",2.0 1337,is about the most ,-1 0,massively useful thing ,123 -2,an interstellar hitchhiker can have.,3
以上是如何在Python中讀寫CSV檔?的詳細內容。更多資訊請關注PHP中文網其他相關文章!