將CSV 檔案匯入Python 中的清單
要將CSV(逗號分隔值)檔案匯入Python 中的清單中,您可以利用內建的csv 模組。此模組有助於讀取和寫入 CSV 檔案。
使用csv 模組
以下是如何使用csv 模組將CSV 檔案匯入清單的簡單範例:
import csv # Open the CSV file with open('file.csv', newline='') as f: # Initialize the CSV reader reader = csv.reader(f) # Convert the contents of the CSV file into a list data = list(reader) # Print the list of records print(data)
輸出將是包含CSV中每一行的列表的列表文件。例如,如果 CSV 檔案包含以下行:
This is the first line,Line1 This is the second line,Line2 This is the third line,Line3
資料清單將為:
[['This is the first line', 'Line1'], ['This is the second line', 'Line2'], ['This is the third line', 'Line3']]
轉換為元組
如果您需要元組列表而不是列表,則可以使用列表理解將列表轉換為tuples:
# Convert `data` from a list of lists to a list of tuples data = [tuple(row) for row in data]
Python 2 註釋
這些示例適用於Python 3。對於 Python 2,開啟檔案時可能需要使用 rb 模式和 your_list 變數而不是資料:
with open('file.csv', 'rb') as f: reader = csv.reader(f) your_list = list(reader)
以上是如何將 CSV 檔案匯入 Python 清單?的詳細內容。更多資訊請關注PHP中文網其他相關文章!