Friday, September 15, 2023
HomePythonExactly how to Add a Thesaurus to a Non-Existent CSV Submit

Exactly how to Add a Thesaurus to a Non-Existent CSV Submit


Adding information to a CSV data is an usual job in information handling. Yet what happens if the CSV data does not exist yet? Right here’s a detailed overview on just how to add a thesaurus to a non-existent CSV data making use of Python’s csv component.

Prerequisites:

Action 1: Import CSV and also OS Python Libraries

 import csv
import os

Action 2: Inspect if the CSV Data Exists

Prior to adding information, inspect if the data exists making use of the os.path.exists() feature. We’ll utilize it in the following action.

Action 3: Produce a Feature to Add the Thesaurus to the CSV Data

If the data does not exist, you’ll require to create the headers (thesaurus tricks) initially. If it does exist, just add the information.

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

# Open up the data in append setting.
with open( filename, 'a', newline="") as csvfile:.
author = csv.DictWriter( csvfile, fieldnames= data_dict. tricks()).

# If data does not exist, create the headers initially.
otherwise file_exists:.
writer.writeheader().

# Create the thesaurus information.
writer.writerow( data_dict)

Action 4: Make Use Of the Feature

Currently, you can utilize the feature to add a thesaurus to your CSV data. If the data does not exist, it will certainly be developed.

 information = {"Call": "John", "Age": 30, "City": "New york city"}
append_dict_to_csv(' data.csv', information)

Tip 5: Confirm

Open Up the data.csv data to validate that the thesaurus has actually been added appropriately. If the data really did not exist previously, you must see it developed in the defined directory site with the thesaurus information.


If you wish to maintain boosting your Python abilities, look into our cost-free e-mail academy:


RELATED ARTICLES

Most Popular

Recent Comments