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.
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.
The csv module is included in Python's standard library, so you can use it by adding an import.
The with syntax is useful for file operations. The close process can be omitted.
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
.
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.
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.
print (amount)
is for checking the operation.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 of
w` 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
''`.
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