Home > Backend Development > Python Tutorial > How Can I Import a CSV File into a List in Python?

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

Mary-Kate Olsen
Release: 2024-12-01 16:11:12
Original
696 people have browsed it

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

Importing a CSV File into a List in Python

To import a CSV (Comma-Separated Values) file into a list in Python, you can utilize the built-in csv module. This module facilitates reading and writing of CSV files.

Using the csv Module

Here's a simple example of how to import a CSV file into a list utilizzando the csv module:

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)
Copy after login

The output will be a list of lists containing each row in the CSV file. For example, if the CSV file contains the following lines:

This is the first line,Line1
This is the second line,Line2
This is the third line,Line3
Copy after login

The data list will be:

[['This is the first line', 'Line1'], ['This is the second line', 'Line2'], ['This is the third line', 'Line3']]
Copy after login

Converting to Tuples

If you require a list of tuples instead of lists, you can use a list comprehension to convert the list to tuples:

# Convert `data` from a list of lists to a list of tuples
data = [tuple(row) for row in data]
Copy after login

Notes for Python 2

These examples are for Python 3. For Python 2, you may need to use the rb mode when opening the file and the your_list variable instead of data:

with open('file.csv', 'rb') as f:
    reader = csv.reader(f)
    your_list = list(reader)
Copy after login

The above is the detailed content of How Can I Import a CSV File into a List in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template