File in python #2 : The interaction between user input, Read CSV file

in #utopian-io6 years ago

Repository

https://github.com/python

What Will I Learn?

  • The interaction between user input
  • Read CSV file

Requirements

  • Basic Python
  • Install Python 3
  • Install Flask

Resources

Difficulty

Basic

Tutorial Content

This tutorial is an advanced series from the previous tutorial. In this tutorial, we will make a more interactive application. In the previous tutorial, we learned how to play with files and access files with different modes. For those of you who are new to python, I recommend you to follow the previous tutorial from the basics. the tutorial is in the curriculum section. Well, let's just start the following tutorial.

Interaction between user and file

In this section, we will learn how to connect user interactions with files. I will create an example to create a list based on user input. The following is an example of the code:

file.py

file = open('example.txt', 'a+')

## function to add list
def addList(text):
    file.write('\n' + text)
    dataInput()

## function to input data
def dataInput():
    addList(input('What Your list ?'))

## Execute function
dataInput()
  • As we learned before we can combine the contents of files with new content. therefore we will use the write function in mode 'a+', like this one open('example.txt', 'a+').

  • Then create a function that is used to write in the file example.txt. The function is addList(text), in this function we pass a parameter (text) containing data input from the user and then we will use the write function to write the data in the file example.txt file.write('\n' + text). Important to remember, because we will write a list in our file. then we need to recall the input that will be filled in by the user. The function that handles it is dataInput ()

  • dataInput() This function is responsible for storing data input from the user. We can use the input() function provided by python. We have finished making two functions that have their respective tasks. now we will run the dataInput() function. We can see the results as shown below:

ezgif.com-video-to-gif.gif

We enter data for Chicken, tomato, sossis and we can see the results of the input printed in the file example.txt

Screenshot_6.png

Read CSV file

We increase our learning about files in python. In the previous section, we are still using files with the extension .txt, This time we will learn how to read files that have the extension .csv.

  • Generating CSV file

Before we play with CSV files we need to create a CSV file that contains real data so we can use it, for that, I suggest you create CSV data on the mockaroo website. I usually use mockaroo to generate data that is used during development. We can see the picture below for an explanation of how to generate a .csv file.

Screenshot_1.png

As we saw in the picture above I will generate 30 data that we will use for development purposes. The following is the data that we have successfully generated in CSV:

data.csv

id,first_name,last_name
1,Leo,Hampton
2,Wake,Fynes
3,Parnell,Frome
4,Bellanca,Brewse
5,Bertrand,Lovell
6,Elsworth,Challace
7,Cole,Jeacock
8,Ema,Feavearyear
9,Evanne,McIan
10,Hynda,Haugg
11,Wolfy,Westmancoat
12,Sim,Walklott
13,Rodge,Quiddington
14,Ynez,Righy
15,Nicolai,Rhucroft
16,Lynnea,McCarle
17,Sebastien,Vasin
18,Davis,Dominick
19,Kathi,MacColgan
20,Demott,Lello
21,Delphinia,Spensly
22,Audrye,Climar
23,Alvis,Tredget
24,Jory,Rasch
25,Carlin,Clift
26,Rudd,Matushevitz
27,Jamal,Gever
28,Kenon,Ohlsen
29,Rolland,Grayer
30,Martynne,Hinckley


  • Create CSV Reader

We will make a CSV reader, all we need is a module from CSV. We can import it in our application then we will do a loop on the data in the CSV file, for more details, we can see the code as follows:

csvreader.csv

## Import module CSV
import csv

## Ser array for data
data = [] 
 
with open('data.csv', 'r') as filecsv:
    csvreader = csv.reader(filecsv)
    for row in csvreader:
        data.append(row)
    print('Total row : ', csvreader.line_num)
print(data)
  • The first step is to import a CSV module, we can import it like this import csv

  • You need to know the CSV data is in line and each data is separated by commas (,). Therefore we need to hold the data in the form of an array, prepare a variable in the form of an array as follows data = [].

  • with, I use within the code this time, with useful to clean the file or close the file when it is not used anymore, so we combine it with open() with open('data.csv', 'r') as filecsv: and we can give a filecsv alias to be easy to use. The CSV file name is data.csv

  • To read CSV files we can use the reader () function from the CSV module that we imported at the top import csv and then store the result in variable csvreader.

  • Looping data in CSV file : What is done next is to loop the data in the csvreader variable, to do a loop we can use for row in csvreader: and use append function to store the value in variable data, This is more like the array_push () method if I think.

  • Count total row: to find out the number of rows or data in the csv file we can use the line.num method and to print we can do like this print('Total row : ', csvreader.line_num) and all data we store in data variable can be print like this print(data).

  • If you are done with all this code. You can run our application and see the demonstration as shown below

ezgif.com-video-to-gif (1).gif

Screenshot_3.png

As we saw in the picture above, we have done to interact with input user with files and then we have learned how to read files that have the extension .csv using the csv module, I hope you can explore more about the files in python. thank you for following this tutorial, hopefully, it's useful for you. 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 #5: Web development with python #5 : Session in flask and Login and Logout system

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

Proof of work done

https://github.com/milleaduski/python-web-app

Sort:  

Thank you for your contribution @duski.harahap.
We have been reviewing your tutorial and suggest the following points listed below:

  • Your tutorial is very interesting on the subject of phyton how to read a csv file, however there is already a lot of online information on this topic. For exemple here
    However, your tutorial is very well explained and with several print screens with the results.

In the next tutorial bring a more innovative subject on python.
Thanks for your hard work in developing this 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 for the advice, next time I will give a more innovative tutorial and still rarely on the internet.

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!

Coin Marketplace

STEEM 0.21
TRX 0.20
JST 0.034
BTC 91797.35
ETH 3122.69
USDT 1.00
SBD 2.98