I got the name of the restaurant The Ranking.csv file exists and the entered restaurant name is in the Ranking.csv file I don't know how to write to csv by adding count +1 to the existing restaurant name without adding a row. Help me.
rest_name = str(input())
count = 1
file_exist = os.path.exists('ranking.csv')
if rest_name:
if not file_exist:
with open('ranking.csv', 'w') as csv_file:
fieldnames = ['NAME', 'COUNT']
writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
writer.writeheader()
elif file_exist:
# File Presence
with open('ranking.csv', 'r') as csv_file:
fieldnames = ['NAME', 'COUNT']
reader = csv.DictReader(csv_file, fieldnames=fieldnames)
for row in reader:
if rest_name == row:
with open('ranking.csv', 'a') as csv_file2:
writer = csv.DictWriter(csv_file2, fieldnames=fieldnames)
writer.writerow({'NAME': 5, 'COUNT': 5})
else:
with open('ranking.csv', 'a') as csv_file:
fieldnames = ['NAME', 'COUNT']
writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
writer.writerow({'NAME': rest_name, 'COUNT': count})
>>> import pandas as pd
>>> with open("ranking.csv", "w", encoding="utf-8") as f:
f.write("""NAME,COUNT
Okryugwan, 111
The Great Wall of China, 1
Chicken Donald, 23""")
33
>>> rest = input ("What's your favorite restaurant? :")
What's your favorite restaurant? : Chicken Donald
>>>
>>> df_rank = pd.read_csv("ranking.csv", encoding="utf-8")
>>> df_rank
NAME COUNT
0 Okryugwan 111
The Great Wall of China 1
2 Chicken Donald 23
>>> if rest in list(df_rank.NAME):
df_rank.loc[df_rank["NAME"] == rest, "COUNT"] += 1
else:
df_rank.loc[len(df_rank)] = [ rest, 1 ]
>>> df_rank
NAME COUNT
0 Okryugwan 111
The Great Wall of China 1
2 Chicken Donald 24
>>> # Chicken Donald has increased by one.
>>> rest = input ("What's your favorite restaurant? :")
What is your favorite restaurant? : Burger King
>>> if rest in list(df_rank.NAME):
df_rank.loc[df_rank["NAME"] == rest, "COUNT"] += 1
else:
df_rank.loc[len(df_rank)] = [ rest, 1 ]
>>> df_rank
NAME COUNT
OkRyuGwan 111 0
The Great Wall 1 1.
2 24 dakttonaldeu
Three Burger King 1.
>>> df_rank.to_csv("ranking.csv", encoding="utf-8", index=False)
>>> df_rank = pd.read_csv("ranking.csv", encoding="utf-8")
>>> df_rank
NAME COUNT
OkRyuGwan 111 0
The Great Wall 1 1.
2 닭도날드 24
Three Burger King 1.
>>>
© 2024 OneMinuteCode. All rights reserved.