Home  >  Article  >  Backend Development  >  How to read and write csv files in Python

How to read and write csv files in Python

PHPz
PHPzforward
2023-06-26 13:09:596181browse

To write to CSV in Python, use Python’s csv module.

For example, let's write a list of strings to a new CSV file:

import csv
data = ["This", "is", "a", "Test"]
with open('example.csv', 'w') as file:
    writer = csv.writer(file)
    writer.writerow(data)

Therefore, you will see a file named example.csv in the current folder.

4 steps to write CSV in Python

To write a CSV file in Python:

1. With Open the CSV file in write mode. This happens using the open() function. Give it the path to the file as the first argument. Specify the mode as the second argument ("r" for read, "w" for write).
2. Create a CSV writer object. To do this, create a writer() object of the csv module and pass the open file as its argument.
3. Write data to CSV file. Use the writerow() function of the writer object to write data to the CSV file.
4. Close the CSV file, using the file's close() method.

Here is an example illustrating this process:

import csv
# 1.
file = open('test.csv', 'w')
# 2.
writer = csv.writer(file)
# 3.
data = ["This", "is", "a", "Test"]
writer.writerow(data)
# 4.
file.close()

This code creates a file named test.csv in the current folder.

If the specified file does not exist, the open() function will open a new file. If so, the existing file is opened.

Shorthand

To reduce the time it takes to write to CSV, open the file using the with statement. This way you don't have to worry about closing the file yourself. with will handle this part automatically.

For example:

import csv
# 1. step
with open('test.csv', 'w') as file:
    # 2. step
    writer = csv.writer(file)
    # 3. step
    data = ["This", "is", "a", "Test"]
    writer.writerow(data)

This will create a new CSV file named test.csv in the current folder and write the list of strings into it.

How to write non-ASCII characters to CSV in Python

By default, you cannot write non-ASCII characters to a CSV file.

To support writing non-ASCII values ​​to a CSV file, specify the character encoding as the third parameter in the open() call.

with open('PATH_TO_FILE.csv', 'w', encoding="UTF8")

The rest of the process follows the steps you learned earlier.

How to create headers for CSV files

So far, you have created CSV files that lack structure.

In Python, you can write headers for any CSV file using the

writerow() function for writing any data to CSV.

Example: Let’s create a sample CSV file containing student data.

In order to effectively build the data, you need to create a header for students at the beginning of the CSV file and insert it. You can follow the same steps as before to write the data to a CSV file and you're done.

Here is the code:

import csv
# Define the structure of the data
student_header = ['name', 'age', 'major', 'minor']
# Define the actual data
student_data = ['Jack', 23, 'Physics', 'Chemistry']
# 1. Open a new CSV file
with open('students.csv', 'w') as file:
    # 2. Create a CSV writer
    writer = csv.writer(file)
    # 3. Write data to the file
    writer.writerow(student_header)
    writer.writerow(student_data)

This will create the students.csv file into the folder you are currently working in. The new file will look like this:

How to read and write csv files in Python

How to write multiple lines to a CSV file in Python

In Python you can use the writerows of the CSV writer () function writes multiple rows to a CSV file simultaneously.

example. Let's say you want to write multiple rows of data to a CSV file. For example, you might have a list of students instead of just one.

To write multiple rows of data to CSV, use the writerows() method.

Here is an example:

import csv
student_header = ['name', 'age', 'major', 'minor']
student_data = [
    ['Jack', 23, 'Physics', 'Chemistry'],
    ['Sophie', 22, 'Physics', 'Computer Science'],
    ['John', 24, 'Mathematics', 'Physics'],
    ['Jane', 30, 'Chemistry', 'Physics']
]
with open('students.csv', 'w') as file:
    writer = csv.writer(file)
    writer.writerow(student_header)
    # Use writerows() not writerow()
    writer.writerows(student_data)

This will generate a new CSV file that looks like this:

How to read and write csv files in Python

How to do it in Python Write the dictionary to the CSV file

Using the DictWriter object can write the dictionary to the CSV file in Python, including the following three steps:

1. Use the DictWriter object of the csv module and which specifies the field name.

2. Use the writeheader() method to create a header into a CSV file.

3. Use the writerows() method to write dictionary data to the file.

Example: Let’s write the student data dictionary to a CSV file.

import csv
student_header = ['name', 'age', 'major', 'minor']
student_data = [
    {'name': 'Jack', 'age': 23, 'major': 'Physics', 'minor': 'Chemistry'},
    {'name': 'Sophie', 'age': 22, 'major': 'Physics', 'minor': 'Computer Science'},
    {'name': 'John', 'age': 24, 'major': 'Mathematics', 'minor': 'Physics'},
    {'name': 'Jane', 'age': 30, 'major': 'Chemistry', 'minor': 'Physics'}
]
with open('students.csv', 'w') as file:
    # Create a CSV dictionary writer and add the student header as field names
    writer = csv.DictWriter(file, fieldnames=student_header)
    # Use writerows() not writerow()
    writer.writeheader()
    writer.writerows(student_data)

Now the result is the same as the students.csv file in the previous example:

How to read and write csv files in Python

Conclusion

CSV or comma separated values ​​is a Commonly used file formats. It consists of values ​​usually separated by commas.

To write CSV in Python, you need to use the csv module by following these steps:

1. Open the CSV file in write mode.

2. Create a CSV writer object.

3. Write data to CSV file.

4. Close the CSV file.

This is a practical example.

import csv
data = ["This", "is", "a", "Test"]
with open('example.csv', 'w') as file:
    writer = csv.writer(file)
    writer.writerow(data)

Happy coding!

The above is the detailed content of How to read and write csv files in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete