Search code examples
pythonpython-3.xfwrite

My python text file appears as empty


This is the code I wrote. After having written name and hb to file, I expected to be able to view the content of the text file I created.

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")

After I ran the code in SHELL, I get this result:

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

Of course, the test1 and test11 values were what I typed in once the code asked me for the input.

Also, when I open the txt file in Notepad I find this:

User:  e
HB:    e

What am I doing wrong here?


Solution

  • Print out your n and h in "for n,h in zip(name,hb)".

    You'll see, that zip give you an amount of tuples. As your opening the file again and again, it will get overridden (as you dont use append mode).

    Have a look at: https://docs.python.org/2/tutorial/inputoutput.html