Home >Backend Development >Python Tutorial >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)
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
The data list will be:
[['This is the first line', 'Line1'], ['This is the second line', 'Line2'], ['This is the third line', 'Line3']]
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]
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)
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!