简体   繁体   English

现有文件未附加新记录

[英]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. 请注意,我将您的input语句更改为raw_input。 I'm using Python 2.7. 我正在使用Python 2.7。 Main things needed: 需要的主要内容:

  1. a choice to exit outside AND inside the while loop 在while循环内和AND外退出的选择
  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 . 这意味着调用newUser() ,并且当以布尔值评估的newUser()的返回值返回True执行缩进代码。 That is bool(newUser()) is True . 那是bool(newUser()) is True

Now the questions are 现在的问题是

a) What does newUser() return and, b) What does bool() mean? a) newUser()返回什么,b) bool()是什么意思?

First b: All objects in Python have some "boolean" value associated with it, True or False . 首先b:Python中的所有对象都有与之关联的“布尔”值TrueFalse 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 . 例如,在布尔上下文中,整数0被视为False ,而任何非零整数都被视为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. 类似地,在布尔值上下文中,空列表[]False (这就是为什么我们可以编写诸如if not my_list: ...来测试列表是否为空)之类的东西,而任何非空列表都被视为True等的原因。

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). 您的newUser()函数不会显式返回任何结果,因为您没有return语句(汤姆的解决方案中添加了一些)。 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. 您想要做的是在添加新用户时返回True -ish值,在不添加新用户时返回False -ish值。 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 . 但是,由于您什么都不返回,因此,如果您没有显式return Python,则函数的默认返回值是一个名为None的值,并且始终为False

So the end result is that the code under your while statement is never run. 因此,最终结果是while语句下的代码永远不会运行。

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). 如果您不确定自己的代码在做什么,请使用pdb调试器逐行浏览代码并确切查看其功能-返回什么函数以及为变量分配什么值pdb会直接您很快就会获得一些不错的教程)。 With Python in particular there's no reason to ever be in the dark about what your code is actually doing. 特别是对于Python,没有理由对您的代码实际上在做什么一无所知。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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