search
HomeBackend DevelopmentPython TutorialHow 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)

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:亿速云. If there is any infringement, please contact admin@php.cn delete
What are some common reasons why a Python script might not execute on Unix?What are some common reasons why a Python script might not execute on Unix?Apr 28, 2025 am 12:18 AM

The reasons why Python scripts cannot run on Unix systems include: 1) Insufficient permissions, using chmod xyour_script.py to grant execution permissions; 2) Shebang line is incorrect or missing, you should use #!/usr/bin/envpython; 3) The environment variables are not set properly, and you can print os.environ debugging; 4) Using the wrong Python version, you can specify the version on the Shebang line or the command line; 5) Dependency problems, using virtual environment to isolate dependencies; 6) Syntax errors, using python-mpy_compileyour_script.py to detect.

Give an example of a scenario where using a Python array would be more appropriate than using a list.Give an example of a scenario where using a Python array would be more appropriate than using a list.Apr 28, 2025 am 12:15 AM

Using Python arrays is more suitable for processing large amounts of numerical data than lists. 1) Arrays save more memory, 2) Arrays are faster to operate by numerical values, 3) Arrays force type consistency, 4) Arrays are compatible with C arrays, but are not as flexible and convenient as lists.

What are the performance implications of using lists versus arrays in Python?What are the performance implications of using lists versus arrays in Python?Apr 28, 2025 am 12:10 AM

Listsare Better ForeflexibilityandMixdatatatypes, Whilearraysares Superior Sumerical Computation Sand Larged Datasets.1) Unselable List Xibility, MixedDatatypes, andfrequent elementchanges.2) Usarray's sensory -sensical operations, Largedatasets, AndwhenMemoryEfficiency

How does NumPy handle memory management for large arrays?How does NumPy handle memory management for large arrays?Apr 28, 2025 am 12:07 AM

NumPymanagesmemoryforlargearraysefficientlyusingviews,copies,andmemory-mappedfiles.1)Viewsallowslicingwithoutcopying,directlymodifyingtheoriginalarray.2)Copiescanbecreatedwiththecopy()methodforpreservingdata.3)Memory-mappedfileshandlemassivedatasetsb

Which requires importing a module: lists or arrays?Which requires importing a module: lists or arrays?Apr 28, 2025 am 12:06 AM

ListsinPythondonotrequireimportingamodule,whilearraysfromthearraymoduledoneedanimport.1)Listsarebuilt-in,versatile,andcanholdmixeddatatypes.2)Arraysaremorememory-efficientfornumericdatabutlessflexible,requiringallelementstobeofthesametype.

What data types can be stored in a Python array?What data types can be stored in a Python array?Apr 27, 2025 am 12:11 AM

Pythonlistscanstoreanydatatype,arraymodulearraysstoreonetype,andNumPyarraysarefornumericalcomputations.1)Listsareversatilebutlessmemory-efficient.2)Arraymodulearraysarememory-efficientforhomogeneousdata.3)NumPyarraysareoptimizedforperformanceinscient

What happens if you try to store a value of the wrong data type in a Python array?What happens if you try to store a value of the wrong data type in a Python array?Apr 27, 2025 am 12:10 AM

WhenyouattempttostoreavalueofthewrongdatatypeinaPythonarray,you'llencounteraTypeError.Thisisduetothearraymodule'sstricttypeenforcement,whichrequiresallelementstobeofthesametypeasspecifiedbythetypecode.Forperformancereasons,arraysaremoreefficientthanl

Which is part of the Python standard library: lists or arrays?Which is part of the Python standard library: lists or arrays?Apr 27, 2025 am 12:03 AM

Pythonlistsarepartofthestandardlibrary,whilearraysarenot.Listsarebuilt-in,versatile,andusedforstoringcollections,whereasarraysareprovidedbythearraymoduleandlesscommonlyusedduetolimitedfunctionality.

See all articles

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

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function