我是python的新手,并试图在路上学习它,我试图使用python和pandas制作一个数据输入电话簿。
这是我写的代码:import pandas as pd
Book = pd.read_csv(r'/Users/denisvirnik/VSCODE/Py/Projects/Book.csv')
start = True
while(start):
print("1: Add a new contact: ")
print("2. View contacts: ")
print("3. Exit ")
op = input("Which option you want to do?: ")
if(op == "1"):
name = input("Type the first name: ")
lastName = input("Type the last Name: ")
phoneNumber = input("Type the Phone Number: ")
data = {
'FristName,': [name],
'LastName,': [lastName],
'PhoneNumber,': [phoneNumber]
}
df = pd.DataFrame(data)#makes the data frame of the user input above
df.to_csv(r'/Users/denisvirnik/VSCODE/Py/Projects/Book.csv', mode='a', index=False, header=False)# appends data frame to CSV file
print("Contact successfully added.")
if(op == "2"):
print(Book.head())
if(op == "3"):
start = False
我设置的选项之一是查看电话簿(代码中的选项2),但是如果我在电话簿中输入新数据,然后尝试查看它而不终止程序并再次运行它,它不会显示,希望也许有人知道一种方法来刷新电话簿中的数据,就像我输入新数据一样。
您可能希望对book和df使用相同的变量,以便输入新数据并查看它。
当op == 2时,您也想读取book
。
除此之外,你没有正确地将数据写入数据框架。
我不会给你一个完整的答案。但是,您可以从下面的代码片段开始:import pandas as pd
start = True
while(start):
print("1: Add a new contact: ")
print("2. View contacts: ")
print("3. Exit ")
op = input("Which option you want to do?: ")
if(op == "1"):
book = pd.read_csv('book.csv')
first_name = input("Type the first name: ")
last_name = input("Type the last Name: ")
phone_number = input("Type the Phone Number: ")
'''
Make sure you are writing information
to the dataframe correctly
'''
# Write your code
# appends data frame to CSV file
book.to_csv('book.csv', mode='a', index=False, header=False)
print("Contact successfully added.")
if(op == "2"):
book = pd.read_csv('book.csv')
print(book.head())
if(op == "3"):
start = False