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 = 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. 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:
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:
data = [f"{name}", f"{usr}", f"{passw}"]
df.loc[len(df)] = data
df.to_csv("dataframe.csv", index=False)