[英]Refreshing data from csv in python using pandas
I'm new to python and trying to learn it on the go, i'm tring to make a data entry phonebook using python with pandas.我是python的新手,并试图在旅途中学习它,我正在尝试使用python和pandas制作一个数据输入电话簿。
There is the code I wrote:有我写的代码:
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
One of the options i've set is to view the phonebook(option 2 in the code), but if i enter new data into the phonebook and then try to view it without terminating the program and running it again it won't show, hope that maybe someone knows a way to refresh the data in the phonebook just as i enter new data into it.我设置的选项之一是查看电话簿(代码中的选项 2),但如果我在电话簿中输入新数据然后尝试查看它而不终止程序并再次运行它就不会显示,希望也许有人知道一种方法来刷新电话簿中的数据,就像我在其中输入新数据一样。
You may want to use the same variable for book and df in order to enter new data and view it.您可能希望对 book 和 df 使用相同的变量,以便输入新数据并查看它。
You also want to read book
when op == 2.当 op == 2 时,您还想
book
。
In addition to that, you are not writing data into dataframe correctly.除此之外,您没有正确地将数据写入数据帧。
I am not giving you a full answer.我没有给你一个完整的答案。 But, you can start with this code snippet.
但是,您可以从这个代码片段开始。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.