如何在不覆盖已存在的所有内容的情况下保存为.txt文件?

时间:2016-02-18 19:48:07

标签: python

我在空闲时间制作应该只是一个非常基本的操作系统。但是,我正在努力使您拥有所需数量的用户,但每次创建新用户时,都会删除旧用户。到目前为止,我有这个:

def typer():
    print("Start typing to get started. Unfortunately, you cannot currently save your files.")
    typerCMD = input("  ")
    CMDLine()


def CMDLine():
    print("Hello, and welcome to your new operating system. Type 'help' to get started.")
    cmd = input("~$: ")
    if cmd == ("help"):
        print("Use the 'leave' command to shut down the system. Use the 'type' command to start a text editor.")
    cmdLvl2 = input("~$: ")
    if cmdLvl2 == ("leave"):
        quit()
    if cmdLvl2 == ("type"):
        typer()

def redirect():
    signIn()

def mUserRedirect():
    makeUser()

def PwordSignIn():
    rPword = input("Password: ")
    with open('passwords.txt', 'r') as f:
        for line in f:
            print(line)
            if rPword == (line):
                CMDLine()
            else:
                print("Incorrect password.")
                signIn()

def signIn():
    rUname = input("Username: ")
    with open('usernames.txt', 'r') as f:
        for line in f:
            print(line)
            if rUname == (line):
                PwordSignIn()
            else:
                print("Username not found.")
                mUserRedirect()

def makeUser():
    nUname = input("New username: ")
    nPword = input("Create a password for the user: ")

    with open('usernames.txt', 'w') as f:
        f.write(nUname)
    with open('passwords.txt', 'w') as f:
        f.write(nPword)
    signIn()

print("Create a new user? (Y/N) ")
nUser = input("")
if nUser == ("N"):
    signIn()
if nUser == ("n"):
    signIn()
if nUser == ("Y"):
    makeUser()
if nUser == ("y"):
    makeUser()

那么如何在不删除已存在的所有内容的情况下写入文件?

1 个答案:

答案 0 :(得分:1)

这取决于您在打开文件时使用的“模式”。来自documentation

  
      
  • 'r'开放阅读(默认)
  •   
  • 'w'打开写入,先截断文件
  •   
  • 'a'打开以进行写入,如果文件存在则附加到文件的末尾
  •   

所以你现在要做的就是:

with open('usernames.txt', 'a') as f:
    f.write(nUname)