[英]Appending a row in csv file with python (PANDA)
As the title suggests I am trying to add a row to an already existing csv file created in python using pandas with: df.to_csv("dataframe.csv", index=False, header=True)
, and looking around the internet I found this method:正如标题所暗示的,我正在尝试将一行添加到使用
df.to_csv("dataframe.csv", index=False, header=True)
在 python 中创建的现有 csv 文件中: df.to_csv("dataframe.csv", index=False, header=True)
,并环顾互联网我发现这种方法:
df = pd.DataFrame([], columns=[f"{name}", f"{usr}", f"{passw}"])
df.to_csv("dataframe.csv", mode="a", header=False)
but when I look at the csv file nothing happens.但是当我查看 csv 文件时,什么也没有发生。 Am I doing something wrong?
难道我做错了什么? I am going to include the entire function even though I don't think it matters that much
我将包括整个功能,即使我认为它没有那么重要
# Takes the user input and appends it to the csv file (this is where I have the problem)
def usr_input():
name = input("Website name: ")
usr = input("Email or username: ")
passw = input("Password: ")
df = pd.DataFrame([], columns=[f"{name}", f"{usr}", f"{passw}"])
df.to_csv("dataframe.csv", mode="a", header=False)
flag = input("Add another one? (y/n): ")
if flag == "y":
usr_input()
else:
quit()
This is where I create the csv file:这是我创建 csv 文件的地方:
def init():
if not os.path.isfile("dataframe.csv"):
df = pd.DataFrame([], columns=["Name", "Email / Username", "Password"])
df.to_csv("dataframe.csv", index=False, header=True)
else:
usr_input()
Found the answer!找到答案了! I just needed to use the loc[] function:
我只需要使用 loc[] 函数:
data = [f"{name}", f"{usr}", f"{passw}"]
df.loc[len(df)] = data
df.to_csv("dataframe.csv", index=False)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.