How to Append a Dictionary to a Non-Existent CSV File

4.5/5 - (2 votes)

Appending data to a CSV file is a common task in data processing. But what if the CSV file doesn’t exist yet? Here’s a step-by-step guide on how to append a dictionary to a non-existent CSV file using Python’s csv module.


πŸ§‘β€πŸ’» Step 1: Import CSV and OS Python Libraries

   import csv
   import os

πŸ§‘β€πŸ’» Step 2: Check if the CSV File Exists

Before appending data, check if the file exists using the os.path.exists() function. We’ll use it in the next step. πŸ‘‡

πŸ§‘β€πŸ’» Step 3: Create a Function to Append the Dictionary to the CSV File

If the file doesn’t exist, you’ll need to write the headers (dictionary keys) first. If it does exist, simply append the data.

   def append_dict_to_csv(filename, data_dict):
       # Check if file exists
       file_exists = os.path.exists(filename)

       # Open the file in append mode
       with open(filename, 'a', newline='') as csvfile:
           writer = csv.DictWriter(csvfile, fieldnames=data_dict.keys())

           # If file doesn't exist, write the headers first
           if not file_exists:

           # Write the dictionary data

πŸ§‘β€πŸ’» Step 4: Use the Function

Now, you can use the function to append a dictionary to your CSV file. If the file doesn’t exist, it will be created.

   data = {"Name": "John", "Age": 30, "City": "New York"}
   append_dict_to_csv('data.csv', data)

πŸ§‘β€πŸ’» Step 5: Verify

Open the data.csv file to verify that the dictionary has been appended correctly. If the file didn’t exist before, you should see it created in the specified directory with the dictionary data.

If you want to keep improving your Python skills, check out our free email academy: