首頁 > 後端開發 > Python教學 > 如何將 CSV 檔案匯入 Python 清單?

如何將 CSV 檔案匯入 Python 清單?

Mary-Kate Olsen
發布: 2024-12-01 16:11:12
原創
739 人瀏覽過

How Can I Import a CSV File into a List in Python?

將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中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板