Dealing with files is standard for many programming tasks. In Python, creating and manipulating .csv files is a straightforward process, thanks to the built-in csv module. In this tutorial, we will learn how to create a CSV file in any directory using Python.
Step 1: Import Required Modules
First, we need to import the csv and os modules which are built-in Python libraries. This can be accomplished using the import statement. The csv module gives us ways to manipulate csv files while the os module enables us to interact with the underlying operating system in various ways.
1 2 |
import csv import os |
Step 2: Define the Directory and Filename
Now, we need to define the directory path where we want our CSV file to be created. Then, we define the name of the file. You can change these to match your needs.
1 2 |
dir_path = "/path/to/your/directory" file_name = "myfile.csv" |
Step 3: Create the Full File Path
Next, we will create the full file path by combining the directory path and the file name using the os.path.join() function.
1 |
file_path = os.path.join(dir_path, file_name) |
Step 4: Create and Write to the CSV File
With the file path ready, the next and final step is to create the CSV file and write data to it. Python’s csv.writer() function allows us to do this easily.
1 2 3 4 5 6 |
with open(file_path, 'w', newline='') as file: writer = csv.writer(file) writer.writerow(["SN", "Name", "Place"]) writer.writerow([1, "John", "Sydney"]) writer.writerow([2, "Eric", "Melbourne"]) writer.writerow([3, "Bob", "Perth"]) |
This code snippet creates a .csv file named “myfile.csv” in the specified directory and writes some rows of data to it.
The Full Code
Here is the full code snippet:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import csv import os dir_path = "/path/to/your/directory" file_name = "myfile.csv" file_path = os.path.join(dir_path, file_name) with open(file_path, 'w', newline='') as file: writer = csv.writer(file) writer.writerow(["SN", "Name", "Place"]) writer.writerow([1, "John", "Sydney"]) writer.writerow([2, "Eric", "Melbourne"]) writer.writerow([3, "Bob", "Perth"]) |
Output:
Conclusion
In this tutorial, we have learned how to create a CSV file in a directory using Python. Using these simple steps, you can quickly generate and store CSV files at any location you need. Experiment with writing different types of data to your CSV and see what you can do with Python’s csv module!