Importing CSV files in Python

Importing CSV Files in Python

CSV (Comma Separated Values) is a commonly used data format for importing data from one program or system to another. In Python, reading and writing CSV files is easy using the appropriate libraries.

This article will explain how to read CSV files using Python. We will use the csv module from the Python standard library to process CSV files.

Preparation

Before you begin writing code, you need to prepare a CSV file. The following is sample data from a sample CSV file:

Name, Age, Gender
John, 28, Male
John, 36, Male
John, 24, Female

Note that each cell is separated by a comma.

Reading a CSV File

To read a CSV file, we will use the reader function of the csv module. Here is a sample code that reads a CSV file and prints it to the console:

import csv

with open('example.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
for row in csv_reader:
if line_count == 0:
print(f'column names are: {", ".join(row)}')
line_count += 1
else:
print(f't{row[0]} is {row[2]}, this year is {row[1]} years old.')
line_count += 1
print(f'number of rows: {line_count}.')

Running this code will output the following:

column names are: name, age, gender
Zhang San is a male, 28 years old.
Li Si is a male, 36 years old.
Wang Wu is a female, 24 years old.
Number of rows: 4.

Note that we open the CSV file in a with statement to ensure that the file is automatically closed after reading. Additionally, we specify a comma as the delimiter in csv.reader.

In the for loop, we iterate over each row in the CSV file. If we are on the first row, we print the column names. If we are not on the first row, we print the data for each row.

Writing a CSV File

To write to a CSV file, we will use the writer function of the csv module. The following is an example code to write data to a CSV file:

import csv

with open('example.csv', mode='w') as csv_file:
fieldnames = ['Name', 'Age', 'Gender']
writer = csv.DictWriter(csv_file, fieldnames=fieldnames)

writer.writeheader()
writer.writerow({'Name': 'Zhang San', 'Age': '28', 'Gender': 'Male'})
writer.writerow({'Name': 'Li Si', 'Age': '36', 'Gender': 'Male'})
writer.writerow({'Name': 'Wang Wu', 'Age': '24', 'Gender': '女'})

Running this code will create a new file named example.csv and write the following data to it:

Name, Age, Gender
John, 28, Male
John, 36, Male
John, 24, Female

Note that we specified the file mode as ‘w’ in the open function, which means we will overwrite the existing file (if it exists) or create a new one (if it doesn’t). We also used csv.DictWriter to format the data in CSV format.

Conclusion

The csv module in Python makes it easy to read and write CSV files. The csv.reader function makes it easy to read CSV files, while the csv.writer function makes it easy to write data to CSV files. Using these functions, you can easily process large amounts of data or import data from one program or system to another.

Leave a Reply

Your email address will not be published. Required fields are marked *