Repository
What Will I Learn?
- Write CSV file
- Read and Write JSON file
Requirements
- Basic Python
- Install Python 3
- Install Flask
Resources
- Python - https://www.python.org/
- Flask - http://flask.pocoo.org/
- Mockaroo - https://www.mockaroo.com/
Difficulty
Basic
Tutorial Content
This tutorial is still related to my previous tutorial about files in python, in the previous tutorial I discussed how to read data with the extension .csv, for those of you who are not at all familiar with python. I suggest you follow my previous tutorial which is in the curriculum section. In this tutorial, I will discuss how to write files with extension .csv using python and not only that we will also intersect with data formats that we use very often, namely JSON. For that, we just start this tutorial.
Write CSV file
What we will learn first is how to write a CSV file, please note that the .csv file is a form of a file that is separated by commas(,). The comma in the CSV file can be interpreted as a column. We can look at the picture below, to illustrate what I call a column:
- Set Column
We will begin our first task, which is writing a column in the CSV file. For methods when opening files we will use the method 'a', keep in mind this method is used so that when we write a file, we do not replace the previous value. for more details, we can see the code below:
csvwriter.py
import csv
## Write
with open('writeData.csv', 'a') as filecsv:
fields = ['Name', 'Lastname', 'age']
writer = csv.DictWriter(filecsv, fieldnames = fields)
Like the code we see above, we must have a reference column as a key to determine the column length of the CSV file that we wrote. The tutorial above we use 3 key columns, They are
fields = ['Name', 'Lastname', 'age']
.After defining the key from the reference column. then we can write the column using the
DictWriter()
method. by using this method, We write CSV data in the form of dictionary. This function has two mandatory parameters, the first is the file to be written and the second parameter is the key pair and the value of the fields to be written in CSV. We can write it like this codecsv.DictWriter(filecsv, fieldnames = fields)
, fieldsname is the default key of the DictWriter function, so you cannot change it and fields are the values of the column to be written.
Write Column
We have defined the column and key that we will use, well then we will write a dictionary based on the column defined earlier. for more details, we can see the code below:
csvwriter.py
import csv
## Write
rows = [
{'Name' : 'Millea', 'Lastname': 'Duski', 'Age' : 23},
{'Name' : 'Sathosi', 'Lastname': 'Nakamoto', 'Age' : 33},
{'Name' : 'Jhon', 'Lastname': 'Doe', 'Age' : 37},
]
with open('writeData.csv', 'a') as filecsv:
fields = ['Name', 'Lastname', 'Age']
writer = csv.DictWriter(filecsv, fieldnames = fields)
writer.writeheader()
writer.writerows(rows)
writeheader()
used to write headers from CSV or key columns that are referenced from the next row.writerows(rows)
used to write rows that refer to the header. This function requires a parameter containing the key and value from the reference column and a new row. We create a variable to store new rows, they are in objects. in this tutorial it is defined as the data below:
rows = [
{'Name' : 'Millea', 'Lastname': 'Duski', 'Age' : 23},
{'Name' : 'Sathosi', 'Lastname': 'Nakamoto', 'Age' : 33},
{'Name' : 'Jhon', 'Lastname': 'Doe', 'Age' : 37},
]
The 'Name' is the name of the reference we have defined in the previous section and 'Millea' is the value of the new row. After that, we can run our programme and we can see the results as shown below:
We can see in the picture above before we did not have the writeData.csv file after we run the program automatically the system creates the file writeData.csv, We have successfully written in the CSV file.
Read and Write JSON file
The next lesson is to write and read JSON format. we'll see some differences when we use .csv and .json files. Discussing files, of course, this one file format should not be missed, because this file format is the one we use most often. This data format is often encountered when we intersect with the API. So we just learned how to read and write this format in python.
- Write JSON
What I will do first is how to write data in JSON format in the format of txt, to access JSON format data we are assisted with a json module import json
that has been built-in python. to write JSON format the method is quite easy, we can see in the code below:
readJSON.py.
import json
data = {}
data["member"] = [
{'Name' : 'Millea', 'Lastname': 'Duski', 'Age' : 23},
{'Name' : 'Sathosi', 'Lastname': 'Nakamoto', 'Age' : 33},
{'Name' : 'Jhon', 'Lastname': 'Doe', 'Age' : 37}
]
with open('member.txt', 'w') as filemember:
json.dump(data, filemember)
- We will write the JSON format into the TXT format file, So from then on I will create an object that contains data in JSON format like this:
data["member"] = [
{'Name' : 'Millea', 'Lastname': 'Duski', 'Age' : 23},
{'Name' : 'Sathosi', 'Lastname': 'Nakamoto', 'Age' : 33},
{'Name' : 'Jhon', 'Lastname': 'Doe', 'Age' : 37}
]
I provide key member data["member"]
in JSON data. but before we have to define variables with object {}
types.
- And as we have learned before we use the
open()
method and the'w'
function to write data and to write JSON data is quite easy by using thedump()
method from module json. The dump function has two mandatory parameters, The first is the data to be written and The second alias of the file that is the place to write data.
If it's finished we can see the results as shown below:
- Read JSON
The next part we will learn how to read JSON files, the method is not much different from how to read CSV files. We will read the file that we have created at the top, that is member.txt. The contents of the member.txt file are data with JSON format. For more details, we can see the code as follows
import json
with open('member.txt', 'r') as filemember:
data = json.load(filemember)
for member in data["member"]:
print("The name is :" + member["Name"] + " and the Age is : " + member["Name"])
As we have learned before to do read data we need the 'r' method and to load data in the member.txt file we can use the
load ()
function and pass the alias from the file to its parametersjson.load(filemember)
.Then we save the data into a variable that we will do looping to see the data inside. We can use
for
to do looping and that must be remembered , the JSON data that we use is wrapped into one key.the key is"member"
, so that we will looping it into something like thisfor member in data["member"]:
and we will loop with each key and print it to show the data.
If there is no mistake, we will see the results as follows:
We can see in the picture above we have succeeded in doing read and write and access to several file formats that we often use in the programming world, I hope you can take lessons from this tutorial, this tutorial is basic, but you can take the information you need this tutorial. Enough to get here, thank you. . .
Curriculum
- Web development with flask
Web developement with python #1 : Flask initialization and Routing system
Web development with python #2 : Templating jinja2 and Method POST on routing system
Web development with python #3 : Get method, Query parameter and Navigate Routing
Web development with python #4: Store cookie and Get cookie in template
Web development with python #6 : Use flash message and combine it with framework boostrap
- File in python
File in python #1 : Read file and Write file and Modes file
File in python #2 : The interaction between user input, Read CSV file
Thank you for your contribution @duski.harahap.
After analyzing your tutorial we suggest the following points below:
The subject of your tutorial how to read a CSV file and how to read and write a Json file already exists many online tutorials. It's a relatively easy subject, yet it's always good for users to know these concepts.
Your tutorial is very well structured and with good demonstration of the results of the developed code.
Thank you for your work in developing this tutorial. We are waiting for your next tutorial.
Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.
To view those questions and the relevant answers related to your post, click here.
Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]
thank you @portugalcoin :)
Thank you for your review, @portugalcoin! Keep up the good work!
Hi @duski.harahap!
Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Feel free to join our @steem-ua Discord server
Hey, @duski.harahap!
Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!
Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).
Want to chat? Join us on Discord https://discord.gg/h52nFrV.
Vote for Utopian Witness!