关于python:我如何保存到.txt文件而不覆盖其中已有的所有内容?

How can I save to a .txt file without overwriting everything that was already in there?

本问题已经有最佳答案,请猛点这里访问。

在我的空闲时间,我正在制作一个非常基本的操作系统。但是,我正在尝试这样做,以便您可以拥有尽可能多的用户,但是每次我创建一个新用户时,它都会删除旧的用户。到目前为止,我有:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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()

那么,我如何才能在不删除文件中已有的所有内容的情况下写入该文件呢?


这取决于打开文件时使用的"模式"。从文档中:

  • 'r' open for reading (default)
  • 'w' open for writing, truncating the file first
  • 'a' open for writing, appending to the end of the file if it exists

所以你现在要做的就是:

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