- Writing to CSV in Python
- Writing to CSV in Python in Detail
- The 4 Steps to Writing a CSV in Python
- The Shorthand Approach
- How to Write Non-ASCII Characters to a CSV in Python
- How to Create a Header for the CSV File
- How to Write Multiple Rows into a CSV File in Python
- How to Write a Dictionary to a CSV File in Python
- Conclusion
- About the Author
- ChatGPT Review (and How to Use It)—A Full Guide (2023)
- 10 Best AI Art Generators of 2023 (Reviewed & Ranked)
- How to Make an App — A Complete 10-Step Guide (in 2023)
- 9 Best Graphic Design Courses + Certification (in 2023)
- 8 Best Python Courses with Certifications (in 2023)
- 8 Best Swift & iOS App Development Courses [in 2023]
- Python Write CSV File
- Steps for writing a CSV file
- Writing to CSV files example
- Writing multiple rows to CSV files
- Writing to CSV files using the DictWriter class
- Summary
Writing to CSV in Python
To write to CSV in Python, use Python’s csv module.
For example, let’s write a list of strings into 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)
As a result, you see a file called example.csv in the current folder.
This was the quick answer. But there is a lot more to cover when it comes to writing CSV files in Python. Let’s jump into the details and see some useful examples.
By the way, if you are interested in becoming a data scientist, check out these awesome Python Data Science courses!
Writing to CSV in Python in Detail
CSV or comma-separated values is a text file. It consists of comma-separated data.
CSV is a useful data format for applications to transfer data. The CSV is a simple lightweight text file. This makes it a perfect fit for sending and receiving data in an efficient way.
For example, you can retrieve data from a database as a CSV. Or you can add a new entry to a database using CSV format.
Here is an example of what CSV data looks like:
However, in this guide, I’m using Mac’s built-in CSV viewer. Thus the CSV data looks more like this:
In the introduction, you saw a simple example of how to write a piece of data into a CSV file. Let’s now take a deeper look at how to write CSV files with Python.
The 4 Steps to Writing a CSV in Python
To write to a CSV file in Python:
- Open a CSV file in the write mode. This happens using the open() function. Give it the path of the file as the first argument. Specify the mode as the second argument ( ‘r’ for read and ‘w’ for write).
- Create a CSV writer object. To do this, create a csv module’s writer() object, and pass the opened file as its argument.
- Write data to the CSV file. Use the writer object’s writerow() function to write data into the CSV file.
- Close the CSV file using the close() method of a file.
Here is an example that illustrates 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 piece of code creates a file called test.csv into the current folder.
The open() function opens a new file if the file specified does not exist. If it does, then the existing file is opened.
The Shorthand Approach
To make writing to CSV a bit shorter, use the with statement to open the file. This way you don’t need to worry about closing the file yourself. The with takes care of that part automatically.
import csv # 1. step with open('example.csv', 'w') as file: # 2. step writer = csv.writer(file) # 3. step data = ["This", "is", "a", "Test"] writer.writerow(data)
This creates a new CSV file called example.csv in the current folder and writes the list of strings to it.
How to Write Non-ASCII Characters to a 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 in the open() call as the third argument.
with open('PATH_TO_FILE.csv', 'w', encoding="UTF8")
The rest of the process follows the steps you learned earlier.
How to Create a Header for the CSV File
So far you have created CSV files that lack the structure.
In Python, it is possible to write a header for any CSV file using the same writerow() function you use to write any data to the CSV.
Example. Let’s create an example CSV file that consists of student data.
To structure the data nicely, create a header for the students and insert it at the beginning of the CSV file. After this, you can follow the same steps from earlier to write the data into a CSV file.
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 creates students.csv file into the folder you are currently working in. The new file looks like this:
How to Write Multiple Rows into a CSV File in Python
In Python, you can use the CSV writer’s writerows() function to write multiple rows into a CSV file on the same go.
Example. Let’s say you want to write more than one line of data into your CSV file. For instance, you may have a list of students instead of only having one of them.
To write multiple lines of data into a CSV, use the writerows() method.
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 results in a new CSV file that looks like this:
How to Write a Dictionary to a CSV File in Python
To write a dictionary into a CSV file in Python, use the DictWriter object by following these three steps:
- Use a csv module’s DictWriter object and specify the field names in it.
- Use the writeheader() method to create the header into the CSV file.
- use the writerows() method to write the dictionary data into the file.
Example. Let’s write a dictionary of student data into a CSV.
import csv student_header = ['name', 'age', 'major', 'minor'] student_data = [ , , , ] 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 students.csv file as in the earlier example:
Conclusion
CSV or comma-separated values is a commonly used file format. It consists of values that are usually separated by commas.
To write into a CSV in Python, you need to use the csv module with these steps:
- Open a CSV file in the write mode.
- Create a CSV writer object.
- Write data to the CSV file.
- Close the CSV file.
Here 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)
Thanks for reading. I hope you find it useful.
About the Author
Hi, I’m Artturi Jalli!
I’m a Tech enthusiast from Finland.
I make Coding & Tech easy and fun with well-thought how-to guides and reviews.
I’ve already helped 5M+ visitors reach their goals!
ChatGPT Review (and How to Use It)—A Full Guide (2023)
ChatGPT is the newest Artificial Intelligence language model developed by OpenAI. Essentially, ChatGPT is an AI-based chatbot that can answer any question. It understands complex topics, like.
10 Best AI Art Generators of 2023 (Reviewed & Ranked)
Choosing the right type of AI art generator is crucial to produce unique, original, and professional artwork. With the latest advancements in AI art generation, you can.
How to Make an App — A Complete 10-Step Guide (in 2023)
Are you looking to create the next best-seller app? Or are you curious about how to create a successful mobile app? This is a step-by-step guide on.
9 Best Graphic Design Courses + Certification (in 2023)
Do you want to become a versatile and skilled graphic designer? This is a comprehensive article on the best graphic design certification courses. These courses prepare you.
8 Best Python Courses with Certifications (in 2023)
Are you looking to become a professional Python developer? Or are you interested in programming but don’t know where to start? Python is a beginner-friendly and versatile.
8 Best Swift & iOS App Development Courses [in 2023]
Are you looking to become an iOS developer? Do you want to create apps with an outstanding design? Do you want to learn to code? IOS App.
Python Write CSV File
Summary: in this tutorial, you’ll learn how to write data into a CSV file using the built-in csv module.
Steps for writing a CSV file
To write data into a CSV file, you follow these steps:
- First, open the CSV file for writing ( w mode) by using the open() function.
- Second, create a CSV writer object by calling the writer() function of the csv module.
- Third, write data to CSV file by calling the writerow() or writerows() method of the CSV writer object.
- Finally, close the file once you complete writing data to it.
The following code illustrates the above steps:
import csv # open the file in the write mode f = open('path/to/csv_file', 'w') # create the csv writer writer = csv.writer(f) # write a row to the csv file writer.writerow(row) # close the file f.close()
Code language: Python (python)
It’ll be shorter if you use the with statement so that you don’t need to call the close() method to explicitly close the file:
import csv # open the file in the write mode with open('path/to/csv_file', 'w') as f: # create the csv writer writer = csv.writer(f) # write a row to the csv file writer.writerow(row)
Code language: PHP (php)
If you’re dealing with non-ASCII characters, you need to specify the character encoding in the open() function.
The following illustrates how to write UTF-8 characters to a CSV file:
import csv # open the file in the write mode with open('path/to/csv_file', 'w', encoding='UTF8') as f: # create the csv writer writer = csv.writer(f) # write a row to the csv file writer.writerow(row)
Code language: PHP (php)
Writing to CSV files example
The following example shows how to write data to the CSV file:
import csv header = ['name', 'area', 'country_code2', 'country_code3'] data = ['Afghanistan', 652090, 'AF', 'AFG'] with open('countries.csv', 'w', encoding='UTF8') as f: writer = csv.writer(f) # write the header writer.writerow(header) # write the data writer.writerow(data)
Code language: PHP (php)
If you open the countries.csv , you’ll see one issue that the file contents have an additional blank line between two subsequent rows:
To remove the blank line, you pass the keyword argument newline=» to the open() function as follows:
import csv header = ['name', 'area', 'country_code2', 'country_code3'] data = ['Afghanistan', 652090, 'AF', 'AFG'] with open('countries.csv', 'w', encoding='UTF8', newline='') as f: writer = csv.writer(f) # write the header writer.writerow(header) # write the data writer.writerow(data)
Code language: PHP (php)
Writing multiple rows to CSV files
To write multiple rows to a CSV file at once, you use the writerows() method of the CSV writer object.
The following uses the writerows() method to write multiple rows into the countries.csv file:
import csv header = ['name', 'area', 'country_code2', 'country_code3'] data = [ ['Albania', 28748, 'AL', 'ALB'], ['Algeria', 2381741, 'DZ', 'DZA'], ['American Samoa', 199, 'AS', 'ASM'], ['Andorra', 468, 'AD', 'AND'], ['Angola', 1246700, 'AO', 'AGO'] ] with open('countries.csv', 'w', encoding='UTF8', newline='') as f: writer = csv.writer(f) # write the header writer.writerow(header) # write multiple rows writer.writerows(data)
Code language: PHP (php)
Writing to CSV files using the DictWriter class
If each row of the CSV file is a dictionary, you can use the DictWriter class of the csv module to write the dictionary to the CSV file.
The example illustrates how to use the DictWriter class to write data to a CSV file:
import csv # csv header fieldnames = ['name', 'area', 'country_code2', 'country_code3'] # csv data rows = [ 'name'
: 'Albania', 'area': 28748, 'country_code2': 'AL', 'country_code3': 'ALB'>, 'name': 'Algeria', 'area': 2381741, 'country_code2': 'DZ', 'country_code3': 'DZA'>, 'name': 'American Samoa', 'area': 199, 'country_code2': 'AS', 'country_code3': 'ASM'> ] with open('countries.csv', 'w', encoding='UTF8', newline='') as f: writer = csv.DictWriter(f, fieldnames=fieldnames) writer.writeheader() writer.writerows(rows) Code language: PHP (php)
- First, define variables that hold the field names and data rows of the CSV file.
- Next, open the CSV file for writing by calling the open() function.
- Then, create a new instance of the DictWriter class by passing the file object ( f ) and fieldnames argument to it.
- After that, write the header for the CSV file by calling the writeheader() method.
- Finally, write data rows to the CSV file using the writerows() method.