I tried to touch the CSV file with Python

Introduction

I've never dealt with Python in my business before, but I heard that using Python can make my business more efficient, so it's very easy, but I tried it out. This time, I focused on the operation of CSV files, which are often used in actual work. (The consideration of abnormal system is omitted)

Click here for the CSV file used this time.

Apple,100,1
Orange,120,4
Banana,80,2
Apple,100,2

From the left, the order is product, amount, and quantity.

Read CSV file

Let's read the CSV file immediately.

import csv

with open('purchase.csv') as f:
    print(f.read())
    
# Apple,100,1
# Orange,120,4
# Banana,80,2
# Apple,100,2

I was able to write in just two lines. As a result, the contents of the file are output as they are.

CSV module

The csv module is included in Python's standard library, so you can use it by adding an import.

with syntax

The with syntax is useful for file operations. The close process can be omitted.

for loop

I will turn it for the time being.

import csv

with open('purchase.csv') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)
        
# ['Apple', '100', '1']
# ['Orange', '120', '4']
# ['Banana', '80', '2']
# ['Apple', '100', '2']

The elements for each line are output as a list.

csv.reader

Use reader to read CSV. You can get the list by turning reader.

Try to take out the contents of the element

If you want to retrieve the element, you should specify the index of row.

import csv

with open('purchase.csv') as f:
    reader = csv.reader(f)
    for row in reader:
        print('Product:' + row[0] + ' ' + 'price:' + row[1] + ' ' + 'Quantity:' + row[2])
        
#Product:Apple price:100 pieces:1
#Product:Orange price:120 pieces:4
#Product:Banana price:80 pieces:2
#Product:Apple price:100 pieces:2

I was able to output each element.

Try to calculate the total amount

I calculated the amount in the for loop and changed it to output the total amount at the end.

import csv

with open('purchase.csv') as f:
    reader = csv.reader(f)
    amount = 0
    for row in reader:
        amount += int(row[1]) * int(row[2])
        print(amount)
print(amount)

# 100
# 580
# 740
# 940
#Total amount: 940 yen

The total amount was output properly.

Write to CSV file

Next time, I would like to write to the CSV file.

import csv

with open('purchase.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerow(['Grape',150,1])
    
# Grape,150,1

I was able to write it safely ... it's all gone! ?? When adding to an existing file, it seems to specify ʻainstead ofw` as an argument.

import csv

with open('purchase.csv', 'a', newline='') as f: #add to
    writer = csv.writer(f)
    writer.writerow(['Grape',150,1])
    
# Apple,100,1
# Orange,120,4
# Banana,80,2
# Apple,100,2
# Grape,150,1

You can now add it.

csv.writer Use writer when writing to csv. Writing can be overwritten or added.

newline In an environment where the line feed code is \ r \ n, it seems safer to specify the argument newline of ʻopen ()as''`.

Finally

This time it's easy, but I touched on the basic reading and writing of CSV files. There are many other things that can be done with Python, so I wanted to take this opportunity to try various things.

Recommended Posts

I tried to touch the CSV file with Python
I tried to divide the file into folders with Python
I tried to touch Python (installation)
[Python] Write to csv file with Python
Output to csv file with Python
I tried to solve the soma cube with python
I tried to solve the problem with Python Vol.1
I tried to find the entropy of the image with python
I tried to simulate how the infection spreads with Python
I tried to touch the COTOHA API
I tried to touch Python (basic syntax)
I tried to solve the ant book beginner's edition with python
I tried to improve the efficiency of daily work with Python
How to read a CSV file with Python 2/3
I tried "differentiating" the image with Python + OpenCV
I tried to save the data with discord
I tried to touch the API of ebay
I tried to get CloudWatch data with Python
I tried to output LLVM IR with Python
I tried "binarizing" the image with Python + OpenCV
I tried reading a CSV file using Python
I tried to automate sushi making with python
I want to write to a file with Python
I tried fp-growth with python
[Python] I tried to visualize the night on the Galactic Railroad with WordCloud!
I tried scraping with Python
I tried to refer to the fun rock-paper-scissors poi for beginners with Python
[Data science basics] I tried saving from csv to mysql with python
I tried to get the authentication code of Qiita API with Python.
I tried with the top 100 PyPI packages> I tried to graph the packages installed on Python
Write to csv with Python
I tried to streamline the standard role of new employees with Python
I tried gRPC with Python
I tried scraping with python
I tried to get the movie information of TMDb API with Python
I tried to touch jupyter
Download csv file with python
I tried to learn the sin function with chainer
I tried to graph the packages installed in Python
I tried to implement Minesweeper on terminal with python
I tried to get started with blender python script_Part 01
I tried to draw a route map with Python
I tried to get started with blender python script_Part 02
I tried to implement an artificial perceptron with python
I want to inherit to the back with python dataclass
How to convert JSON file to CSV file with Python Pandas
[Python] I tried to graph the top 10 eyeshadow rankings
I tried to automatically generate a password with Python3
I tried to analyze J League data with Python
I tried hitting the API with echonest's python client
I tried to summarize the string operations of Python
I tried to solve AOJ's number theory with Python
I tried to easily visualize the tweets of JAWS DAYS 2017 with Python + ELK
I tried searching for files under the folder with Python by file name
I tried to automatically send the literature of the new coronavirus to LINE with Python
I tried to open the latest data of the Excel file managed by date in the folder with Python
Extract the xz file with python
I tried web scraping with python.
I tried to touch Tesla's API
I liked the tweet with python. ..
I want to debug with Python