我的 python 文本文件显示为空

My python text file appears as empty

这是我写的代码。将 namehb 写入文件后,我希望能够查看我创建的文本文件的内容。

run=True
name=[]
hb=[]
list_data=()

def add_new():
    name=input("Name: ")
    hb=input("HB: ")
    for n,h in zip(name,hb):
        list_data=open("p.txt","w")
        list_data.write("User:{0:>3s}\nHB:{1:>5s}\n".format(n,h))
        list_data.close()

while run is True:
    ask1=input("1. View\n2. Add\n3. Edit\n4. Remove\nPick a number: ")
    if ask1=='1':
        if not list_data:
            print("Nothing to view")
        else:
            list_data=open("p.txt","r")
            print(list_data.read())
    elif ask1=='2':
        add_new()
    elif ask1=='3':
        print("WIP")
    elif ask1=='4':
        print("WIP")

在 运行 SHELL 中的代码之后,我得到了这个结果:

1. View
2. Add
3. Edit
4. Remove
Pick a number: 2
Name: test1
HB: test11
1. View
2. Add
3. Edit
4. Remove
Pick a number: 1
Nothing to view

当然,test1test11 值是我在代码要求我输入时输入的值。

此外,当我在记事本中打开 txt 文件时,我发现:

User:  e
HB:    e

我做错了什么?

在 "for n,h in zip(name,hb)" 中打印出你的 n 和 h。

你会看到,那个 zip 给了你一定数量的元组。当您一次又一次打开文件时,它将被覆盖(因为您不使用追加模式)。

看看: https://docs.python.org/2/tutorial/inputoutput.html