python learning

Even an infrastructure engineer like me who is not a development engineer in learning python I would like to recommend udemy's python course, which explains in a very easy-to-understand manner. In particular, the instructor, Jun Sakai, is easy to hear and covers a wide range of content. I am grateful that I can actually mention the code style and learn practical knowledge. (* Personally, I don't think you can understand this even if you read a lot of books on the market.)

https://www.udemy.com/course/python-beginner/

One of the issues is that the robot asks the recommended restaurant in Q & A, writes the answer to CSV, and counts up the number of answers, but this is difficult. .. ..

To be honest, I was once frustrated and threw it here, but recently I had another opportunity to touch Python and my motivation to study rekindled.

It's still far from the completion of the task ahead, but the underlying part of the process of being counted up to CSV has been completed. Keep a memorandum about where you are addicted.

[Fixed part] First of all, the process of counting up the contents entered on CSV cannot be performed. When I tried google, I realized that various people were worried about the same content and the world was small.

Specifically, when I read a file with CSV, I can not write it to the file as it is If you think about it carefully, the open method is called in read mode at the time of reading. I can't write it as it is, but there were some people around here who were addicted to the same thing.

So when you read it, write the read contents to a variable You have to write the exported variables to CSV at the end of the process.

Therefore, the specific processing flow is as follows.

―― 1. Does the CSV file to be output exist or not?

--1-1. If it exists Read all lines of the first existing CSV file --1-1-1. If a key already exists, count up the value of that key, store it in a variable, and finally write it to CSV. --1-1-2. If the key does not exist, write a new key and value to CSV

--1-2. If it does not exist Create a new CSV → This process is easy because it is explained in the above udemy python course

Based on the above, I wrote the following code

import csv
import os

from termcolor import colored

while True:
    print(colored('=' * 20, 'green'))
    print(colored('Which restaurant do you like?', 'green'))
    print(colored('=' * 20, 'green'))
    name = input()
    name = name.title()
    if name:
        break

#Method for creating a new CSV
def new_csv():
    with open('data.csv', 'w', newline='', encoding='utf-8') as csv_file:
        fieldnames = ['Name', 'Count']
        writer = csv.DictWriter(csv_file,fieldnames=fieldnames)
        writer.writeheader()
        writer.writerow({'Name': name,'Count': 1})

#Method to write data variable to CSV at the end
def csv_output():
    with open('data.csv', 'w', newline='', encoding='utf-8') as csv_file:
        fieldnames = ['Name', 'Count']
        writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(data)

#Method for adding new data to CSV
def csv_appending():
    with open('data.csv', 'a', newline='', encoding='utf-8') as csv_file:
        fieldnames = ['Name', 'Count']
        writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
        writer.writerow({'Name': name,'Count': 1})

"""
data.If csv exists, read the CSV contents into the data variable
New if it doesn't exist_call csv method
"""
if os.path.exists('data.csv'):
    with open('data.csv', 'r', newline='', encoding='utf-8') as csv_file:
        reader =csv.DictReader(csv_file)
        data = [row for row in reader]

        #If the key already exists, it counts up, and if it does not exist, it goes through a loop and csv_Call the appending method
        for row in data:
            if row['Name'] == name:
                row['Count'] = int(row['Count']) + 1
                csv_output()
                break
        else:
            csv_appending()
else:
    new_csv()

I've done what I want to do with this, but I think there's probably a better way to write it. And object-oriented? MVC framework? I think that I can write more sophisticated and cool code if I get a little more, but once the base logic part is done, I think that it is the part of how to improve extensibility and visibility. Besides, it may be interesting to add a process to finally aggregate the created CSV file. .. ..

Personally, I'd like some advice because this will make the code even better! !!

Thank you very much.

Recommended Posts

python learning
[Python] Learning Note 1
Python learning notes
python learning output
Python learning site
Python learning day 4
Python Deep Learning
Python learning (supplement)
Deep learning × Python
python learning notes
Learning Python with ChemTHEATER 03
Python module (Python learning memo ④)
Reinforcement learning 1 Python installation
Learning Python with ChemTHEATER 05-1
Python: Deep Learning Practices
Python ~ Grammar speed learning ~
Python
Private Python learning procedure
Learning Python with ChemTHEATER 02
Learning Python with ChemTHEATER 01
Python: Deep Learning Tuning
Python + Unity Reinforcement Learning (Learning)
Python: Supervised Learning (Regression)
Python: Supervised Learning (Classification)
Effective Python Learning Memorandum Day 15 [15/100]
Python exception handling (Python learning memo ⑥)
O'Reilly python3 Primer Learning Notes
Learning flow for Python beginners
Effective Python Learning Memorandum Day 6 [6/100]
Effective Python Learning Memorandum Day 12 [12/100]
Python: Supervised Learning: Hyperparameters Part 1
Python learning plan for AI learning
Effective Python Learning Memorandum Day 9 [9/100]
Effective Python Learning Memorandum Day 8 [8/100]
Reinforcement learning starting with Python
Machine learning with Python! Preparation
Python data analysis learning notes
Effective Python Learning Memorandum Day 14 [14/100]
Effective Python Learning Memorandum Day 1 [1/100]
Python Machine Learning Programming> Keywords
Python: Supervised Learning: Hyperparameters Part 2
Effective Python Learning Memorandum Day 13 [13/100]
Effective Python Learning Memorandum Day 3 [3/100]
Effective Python Learning Memorandum Day 5 [5/100]
Checkio's recommendation for learning Python
Effective Python Learning Memorandum Day 4 [4/100]
Beginning with Python machine learning
Python Iteration Learning with Cheminformatics
Effective Python Learning Memorandum Day 7 [7/100]
Effective Python Learning Memorandum Day 2 [2/100]
Python: Unsupervised Learning: Non-hierarchical clustering
real-time-Personal-estimation (learning)
kafka python
Implement stacking learning in Python [Kaggle]
Python basics ⑤
python + lottery 6
Python Summary
Built-in python
Python technique
Studying python
Python 2.7 Countdown