Skip to content

WebNinjaDeveloper.com

Programming Tutorials




Menu
  • Home
  • Youtube Channel
  • Official Blog
  • Nearby Places Finder
  • Direction Route Finder
  • Distance & Time Calculator
Menu

Python 3 Script to Convert CSV File to YAML File in Command Line

Posted on January 7, 2023

 

 

Welcome folks today in this blog post we will be exporting csv file to yaml and saving it as yaml file inside the root directory in command line using csv module. All the full source code of the application is shown below.

 

 

Get Started

 

 

In order to get started you need to make an app.py file and copy paste the following code

 

 

app.py

 

 

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
import csv
import yaml
 
# Open the CSV file and read the contents
with open('output.csv', 'r') as csv_file:
    csv_reader = csv.reader(csv_file)
    
    # Create an empty list to store the data
    data = []
    
    # Iterate over the rows of the CSV file and append each row to the data list
    for row in csv_reader:
        data.append(row)

 

 

As you can see we are importing the csv and yamlmodule and then we are loading the input csv file called output.csv in read mode. And then we are reading the content of the csv file using the reader() method. And then we are using a simple for loop to write all the contents of the csv file inside a data array. For this we are using the append() method.

 

 

Dumping Data inside YAML File and Saving it

 

 

Now guys we will be opening the yaml file using the open() method and dump all the data present inside the data array into it using the dump() method as shown below

 

 

Python
1
2
3
# Open the YAML file and write the data to it
with open('yaml_file.yaml', 'w') as yaml_file:
    yaml.dump(data, yaml_file)

 

 

Now before running this python script you need to create the output.csv file inside the root directory as shown below

 

output.csv

 

 

1
2
3
4
5
Name,Age,Country
Alice,25,USA
Bob,30,Canada
Claire,35,UK
David,40,Australia

 

 

Now if you execute the python script inside the command line you will see the yaml_file.yaml will be created as shown below

 

 

python app.py

 

 

 

 

 

Recent Posts

  • Android Java Project to Crop,Scale & Rotate Images Selected From Gallery and Save it inside SD Card
  • Android Kotlin Project to Load Image From URL into ImageView Widget
  • Android Java Project to Make HTTP Call to JSONPlaceholder API and Display Data in RecyclerView Using GSON & Volley Library
  • Android Java Project to Download Youtube Video Thumbnail From URL & Save it inside SD Card
  • Android Java Project to Embed Google Maps & Add Markers Using Maps SDK
  • Angular
  • Bunjs
  • C#
  • Deno
  • django
  • Electronjs
  • java
  • javascript
  • Koajs
  • kotlin
  • Laravel
  • meteorjs
  • Nestjs
  • Nextjs
  • Nodejs
  • PHP
  • Python
  • React
  • ReactNative
  • Svelte
  • Tutorials
  • Vuejs




©2023 WebNinjaDeveloper.com | Design: Newspaperly WordPress Theme