简体   繁体   中英

Existing file not appending new record

I am trying to create a file as the header and then open it later to append new records, but it seems I am not doing something correctly, does anyone have an idea?

here is the code below:

I have tried it in several ways to no avail.

file = 'Quizdata5.txt'
users = {}

def header():
    headers = ("USERID      LOGIN-NAME      SURNAME        NAME       AGE  "
               "       YEAR-GROUP     SEX    USERNAME\n")
    with open(file, 'w') as file1:
        file1 .write(headers)
        file1.close()

def newUser():
    global users
    global header
    global createLogin
    global createPassw
    global surname
    global name
    global  age
    global  y_group
    global  sex
    global z1

    createLogin = input("Create login name: ")
    if createLogin in users: # check if login name exists
        print("\nLogin name already exist, please choose a different name!\n")
    else:
        createPassw = input("Create password: ")
        users[createLogin] = createPassw # add login and password
    #return (users[createLogin])
    surname = input("Pls enter your surname: ")
    name = input("Pls enter ur name: ")
    age = input("Pls enter your age: ")
    y_group = int(input("Please enter your year group: "))
    sex =input("Please enter your sex: ")
    print("\nUser created!\n")
    print("*********************************")
    print(" Your Name is\t" + name, "and it starts with: " + name[0] + "\n")
    z1 = createPassw[:3] + age
    print(" Your Username is:\t ", z1)

if __name__ =='__main__':
    header()
    while newUser():
        with open(file, 'a') as file2:
            rows = ("{:8}    {:8}        {:8}        {:8}       {:8}    {:8}"
                    "     {:8}      {:8} \n".format(createLogin, createPassw,
                                                    surname, name, age,
                                                    y_group, sex, z1))
             file2.write(rows.split())
        file2.close()
        #enter code here

Working version below. Note that I changed your input statements to raw_input. I'm using Python 2.7. Main things needed:

  1. a choice to exit outside AND inside the while loop
  2. build a list for existing users for the existing username check
  3. fixing your formatting for row
  4. Not splitting your row when you write it

Seems to be working now and ready for more improvements. Build a little and test until working, then build more - saves a ton of time!

file = 'Quizdata5.txt'
users = {}

def header():
    headers = "USERID    LOGIN-NAME    SURNAME    NAME    AGE    YEAR-GROUP    SEX    USERNAME\n"
    with open(file, 'r') as file1:
        firstLine = file1.readline()
        print firstLine
        if firstLine == headers:
            print 'Headers present'
            return
    with open(file, 'w') as file1:
            file1.write(headers)

def newUser():
    userList = []

    with open(file, 'r') as file1:
        Lines = file1.readlines()
        for line in Lines[1:]:
            lineArray = line.split('    ')
            userList.append(lineArray[0])
        print userList

    global users
    global header
    global createLogin
    global createPassw 
    global surname 
    global name
    global  age
    global  y_group
    global  sex
    global z1

    createLogin = raw_input("Create login name or enter 'exit' to quit: ")
    if createLogin == 'exit':
        return False

    while createLogin in userList: # check if login name exists
        print("\nLogin name already exist, please choose a different name!\n")
        createLogin = raw_input("Create login name or enter 'exit' to quit: ")
        createLogin = createLogin.strip()
        if createLogin == 'exit':
            print('Goodbye for now.')
            return False
    createPassw = raw_input("Create password: ")
    users[createLogin] = createPassw # add login and password
    # return (users[createLogin])
    surname = raw_input("Pls enter your surname: ")
    name = raw_input("Pls enter ur name: ")
    age = raw_input("Pls enter your age: ")
    y_group = int(raw_input("Please enter your year group: "))
    sex = raw_input("Please enter your sex: ")
    print("\nUser created!\n") 
    print("*********************************")
    print(" Your Name is\t" + name, "and it starts with: " + name[0] + "\n")
    z1 = createPassw[:3] + age
    print(" Your Username is:\t ", z1)
    return True

if __name__ =='__main__':
    header()    
    while newUser() == True:
        with open(file, 'a') as file2:
            row ="{a}    {b}    {c}    {d}    {e}    {f}    {g}    {h}\n".format(
                    a=createLogin, b=createPassw, c=surname, d=name, e=age, f=y_group, g=sex, h=z1)
            file2.write(row)

Without just rewriting your code outright, your problem is the line

while newUser():

This means call newUser() , and execute the indented code only if the return value of newUser() , evaluated as a boolean, returns True . That is bool(newUser()) is True .

Now the questions are

a) What does newUser() return and, b) What does bool() mean?

First b: All objects in Python have some "boolean" value associated with it, True or False . For a lot of built-in types their boolean evaluation makes sense. For example the integer 0 is treated as False in a boolean context, while any non-zero integer is treated as True . This is the case in most any programming language with some exceptions.

Similarly an empty list [] is False in a boolean context (which is why we can write things like if not my_list: ... to test if a list is empty) while any non-empty list is treated as True and so on.

As for a:

Your newUser() function doesn't explicitly return and any result, because you don't have a return statement (Tom's solution added some). What you want to do is return a True -ish value when a new user is added, and a False -ish value when no new users are to be added. But since you don't return anything, in fact, the default return value for functions if Python, if you don't explicitly return , is a value called None and it is always False .

So the end result is that the code under your while statement is never run.

If you're ever in doubt about what your code is doing walk through it line by line and see exactly what it's doing--what functions are returning and what values are being assigned to variables--by using the pdb debugger (Google will direct you quickly to some good tutorials). With Python in particular there's no reason to ever be in the dark about what your code is actually doing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM