Home > Back-end >  Numbering or counting the appended lines in python
Numbering or counting the appended lines in python

Time:11-02

I would like to count or add numbers to the file everytime I add something to it.

My file is consist of

 Account|Username|Password

I would like to have it like this whenever the user adds another account.

 #  Account  Username  Password
 1  Facebook  Name    Pass

My code of adding account is this

def add_account():
    acc = input("Enter the name of your account.")
    username = input(f"Enter the username of your {acc}")
    password = input(f"Enter the password of your {acc}")
    ask = input(f" Do you like to save {acc} credentials? Y|N")

    if ask == "Y":
        with open("myfile.txt", "a") as file:
             file.write(""   acc   username   password)
             file.close()

add_accout()

def view_account():
    file = open("myfile.txt", "r")
    line = file.readline()
      for line in file:
          a, b, c, d = line.split("|")
          d = d.strip()
          print(formatStr(a), formatStr(b), formatStr(c), formatStr(d))

view_account()

def formatStr(str):
     nochars = 15
     return str   (" "*(nochars - len(str))

How can I count the appended lines?

CodePudding user response:

As jarmod is suggesting in the comments, you can use a global counting variable to number each added account:

counting = 0
                   
def add_account():
    global counting
    acc = input("Enter the name of your account.")
    username = input(f"Enter the username of your {acc}")
    password = input(f"Enter the password of your {acc}")
    ask = input(f" Do you like to save {acc} credentials? Y|N")

    if ask == "Y":
        counting  = 1
        with open("myfile.txt", "a") as file:
            file.write(""   acc   username   password   str(counting))
            file.close()

add_account()
  • Related