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
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 yaml
module 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
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