Working with Files: Write CSV Files in Python

Data is a crucial part of any organization and it is very important to manage it efficiently, one method in which you can store data is using the CSV(Comma-Separated Values) file. It is a plain text file format used to store tabular data, such as spreadsheets or databases. It is a common file format for exchanging data between different software systems or for data storage.

In the previous article, you learned how to read a CSV file in Python and in this one, you will be learning how to write a CSV file in Python. Till now, you have learned the basics like reading a text file, writing to a text file, creating a file, and checking the existence of a file in Python. This concept is a bit more complex but at the same time easily understandable. In this article, you are going to learn the procedure to write CSV files in Python, so let's get started.

Procedure to Write CSV Files in Python:

To write CSV files in Python, you can use the built-in 'csv' module or the popular 'pandas' library. Here's an example of how to use both methods:

  1. Using the 'csv' module:

    The 'csv' module in Python provides functionality for working with CSV files. Here's a step-by-step breakdown:

a) Import the 'csv' module:

 >>> import csv

b) Open the CSV file:

Use the 'open()' function to open the file in write mode ('w'). Pass the filename or the file path as an argument. In this example, I assume the CSV file is named 'file.csv' and is in the same directory as your Python script.

 >>> with open('file.csv', 'w', newline=' ') as file:

c) Create a CSV writer object:

Use the 'csv.writer()' function, passing the file object as an argument, to create a writer object that will iterate over the rows in the CSV file.

 >>> writer = csv.writer(file)

d) Write data to the CSV file:

Use the 'writerow()' method of the writer object to write each row of data to the CSV file.

 >>> writer.writerow(['Name', 'Age', 'Department'])
 >>> writer.writerow(['Maxwell', 32, 'HR'])
 >>> writer.writerow(['Shivam', 28, 'Finance'])
 >>> writer.writerow(['Sarah Jones', 40, 'Marketing'])

Putting it all together, here's the complete code to write a CSV file using the 'csv' module:

 >>> import csv
 >>> # Open the CSV file in write mode
 >>> with open('file.csv', 'w', newline='') as file:
 >>> # Create a CSV writer object
 >>> writer = csv.writer(file)
 >>> # Write data to the CSV file
 >>> writer.writerow(['Name', 'Age', 'Department'])
 >>> writer.writerow(['John Doe', 32, 'Marketing'])
 >>> writer.writerow(['Jane Smith', 28, 'HR'])
 >>> writer.writerow(['Alex Johnson', 40, 'Finance'])
  1. Using the 'pandas' library:

'pandas' is a powerful data manipulation library in Python. It provides a high-level 'to_csv()' function that simplifies writing CSV files. Here's a step-by-step breakdown:

a) Import the 'pandas' library:

 >>> import pandas as pd

b) Create a DataFrame:

Create a DataFrame object containing the data you want to write to the CSV file. You can specify the data either manually or by reading it from another source. Let's assume you have the following data:

 >>> data = {
'Name': ['Maxwell', 'Shivam', 'Sarah Jones'],
'Age': [32, 28, 40],
'Department': ['HR', 'Finance', 'Marketing'],
'Salary': [50000, 45000, 60000] 
}
 >>> df = pd.DataFrame(data)

c) Write the DataFrame to a CSV file:

Use the 'to_csv()' function from 'pandas' to write the DataFrame to a CSV file. Pass the filename or file path as the first argument. By default, the function will write the index along with the data. You can set 'index=False' to exclude the index from the CSV file.

 >>> df.to_csv('output.csv', index=False)

In this example, the DataFrame will be written to a file named 'output.csv' in the current directory.

Putting it all together, here's the complete code to write a CSV file using 'pandas':

 >>> import pandas as pd
 >>> # Create a DataFrame
 >>> data = {
'Name': ['John Doe', 'Jane Smith', 'Alex Johnson'],
'Age': [32, 28, 40],
'Department': ['Marketing', 'HR', 'Finance'],
'Salary': [50000, 45000, 60000]
}
 >>> df = pd.DataFrame(data)
 >>> # Write the DataFrame to a CSV file
 >>> df.to_csv('output.csv', index = False)

Both methods allow you to write CSV files in Python. It is up to you to decide which method you want to use.

Conclusion:

In conclusion, Python provides convenient methods for writing CSV (Comma-Separated Values) files. The built-in 'csv' module offers a simple approach, allowing you to open a CSV file, create a writer object, and write rows to the file. On the other hand, the 'pandas' library provides a more advanced and efficient way to handle CSV files by writing them into a powerful DataFrame structure.

Overall, Python offers flexible options for writing and working with CSV files, making it an excellent choice for data processing and manipulation tasks. I hope you understand this concept but practice again and again to grasp the concept well. If you have any questions or doubts, feel free to contact us.


Learn via Video Course

Python Logo

Python

6109

7 hrs