Table of Contents
Shorthand
How to write non-ASCII characters to CSV in Python
How to create headers for CSV files
How to write multiple lines to a CSV file in Python
How to do it in Python Write the dictionary to the CSV file
Conclusion
Home Backend Development Python Tutorial How to read and write csv files in Python

How to read and write csv files in Python

Jun 26, 2023 pm 01:09 PM
csv file

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

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

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

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

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

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

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

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

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 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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed operation method of comparing CSV files with Beyond Compare Detailed operation method of comparing CSV files with Beyond Compare Apr 22, 2024 am 11:52 AM

After installing the BeyondCompare software, select the CSV file to be compared, right-click the file and select the [Compare] option in the expanded menu. The text comparison session will be opened by default. You can click the text comparison session toolbar to display the [All [,] Differences [, and [Same]] buttons respectively to view the file differences more intuitively and accurately. Method 2: Open BeyondCompare in table comparison mode, select the table comparison session, and open the session operation interface. Click the [Open File] button and select the CSV file to be compared. Click the inequality sign [≠] button on the toolbar of the table comparison session operation interface to view the differences between the files.

A quick guide to CSV file manipulation A quick guide to CSV file manipulation Dec 26, 2023 pm 02:23 PM

Quickly learn how to open and process CSV format files. With the continuous development of data analysis and processing, CSV format has become one of the widely used file formats. A CSV file is a simple and easy-to-read text file with different data fields separated by commas. Whether in academic research, business analysis or data processing, we often encounter situations where we need to open and process CSV files. The following guide will show you how to quickly learn to open and process CSV format files. Step 1: Understand the CSV file format First,

What does digital currency snapshot mean? Learn more about the digital currency snapshot in one article What does digital currency snapshot mean? Learn more about the digital currency snapshot in one article Mar 26, 2024 am 09:51 AM

For some novice investors who have just entered the currency circle, they will always encounter some professional vocabulary during the investment process. These professional vocabulary are created to facilitate investors’ investment, but at the same time, these vocabulary may also be relatively Hard to understand. The digital currency snapshot we introduce to you today is a relatively professional concept in the currency circle. As we all know, the market of Bitcoin changes very quickly, so it is often necessary to take snapshots to understand the changes in the market and our operating processes. Many investors may still not know what digital currency snapshots mean. Now let the editor take you through an article to understand the digital currency snapshot. What does digital currency snapshot mean? A digital currency snapshot is a moment on a specified blockchain (i.e.

How to solve the problem of garbled characters when importing Chinese data into Oracle? How to solve the problem of garbled characters when importing Chinese data into Oracle? Mar 10, 2024 am 09:54 AM

Title: Methods and code examples to solve the problem of garbled characters when importing Chinese data into Oracle. When importing Chinese data into Oracle database, garbled characters often appear. This may be due to incorrect database character set settings or encoding conversion problems during the import process. . In order to solve this problem, we can take some methods to ensure that the imported Chinese data can be displayed correctly. The following are some solutions and specific code examples: 1. Check the database character set settings In the Oracle database, the character set settings are

How to export the queried data in navicat How to export the queried data in navicat Apr 24, 2024 am 04:15 AM

Export query results in Navicat: Execute query. Right-click the query results and select Export Data. Select the export format as needed: CSV: Field separator is comma. Excel: Includes table headers, using Excel format. SQL script: Contains SQL statements used to recreate query results. Select export options (such as encoding, line breaks). Select the export location and file name. Click "Export" to start the export.

How to read csv files with pycharm How to read csv files with pycharm Apr 03, 2024 pm 08:45 PM

The steps to read CSV files in PyCharm are as follows: Import the csv module. Open the CSV file using the open() function. Use the csv.reader() function to read CSV file contents. Iterate through each row and get the field data as a list. Process the data in the CSV file, such as printing or further processing.

Example of reading and writing CSV files using OpenCSV in Java Example of reading and writing CSV files using OpenCSV in Java Dec 20, 2023 pm 01:39 PM

Example of using OpenCSV to read and write CSV files in Java. CSV (Comma-SeparatedValues) refers to comma-separated values ​​and is a common data storage format. In Java, OpenCSV is a commonly used tool library for reading and writing CSV files. This article will introduce how to use OpenCSV to implement examples of reading and writing CSV files. Introducing the OpenCSV library First, you need to introduce the OpenCSV library to

How to read csv in python How to read csv in python Mar 28, 2024 am 10:34 AM

Reading method: 1. Create a python sample file; 2. Import the csv module, and then use the open function to open the CSV file; 3. Pass the file object to the csv.reader function, and then use a for loop to traverse and read each line of data; 4. , just print each line of data.

See all articles