Lucy Kim
Lucy Kim

Reputation: 35

Python file read and save

I used Python 3.6 version and now I want to save name & age at the file and then read the text as name + tab + age but I can't approach file read side.

My code:

while True:
    print("-------------")
    name=input("Name: ")
    age=input ("Age: ")
    contInput=input("Continue Input? (y/n) ")
    fp.open("test.txt", "a")
    fp.write(name+","+age+"\n")
    if contInput=="n":
        fp.close()
        break
    else:
        continue
with open("test.txt", "r") as fp:
    rd = fp.read().split('\n')
    ????
fp.close()

so I just confuse about file read. I want to print my saved data like below.

name [tab] age

but after used split method, rd type is list. Can I divide name & age as each items?

Upvotes: 1

Views: 121

Answers (1)

John Gordon
John Gordon

Reputation: 33335

fp.open("test.txt", "a")

At this point in your program, fp doesn't exist yet. Perhaps you meant fp = open(...) instead?

You're only closing the file if the user chose not to continue, but you're opening it every time through the loop. You should open and close it only once, or open and close it every time through the loop.

fp.write(name+","+"age"+"\n")

This writes the literal word age instead of the age variable. You probably wanted this instead: fp.write(name + "," + age + "\n")

Try this for your input loop:

with open("test.txt", "r") as fp:
    for line in fp:
        data = line.split(",")
        name = data[0]
        age = data[1]

Upvotes: 4

Related Questions