【问题标题】:Python file read and savePython文件读取和保存
【发布时间】:2018-02-07 23:51:26
【问题描述】:

我使用 Python 3.6 版本,现在我想在文件中保存姓名和年龄,然后将文本读取为姓名 + 制表符 + 年龄,但我无法接近文件读取端。

我的代码:

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

所以我只是对文件读取感到困惑。我想打印我保存的数据,如下所示。

姓名[标签]年龄

但是使用split方法后,rd类型是list。 我可以将姓名和年龄划分为每个项目吗?

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:
    fp.open("test.txt", "a")
    

    此时,在您的程序中,fp 尚不存在。也许您的意思是fp = open(...)

    如果用户选择不继续,您只会关闭文件,但每次循环时您都会打开它。您应该只打开和关闭一次,或者在循环中每次打开和关闭它。

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

    这将写入字面词age 而不是年龄变量。你可能想要这个:fp.write(name + "," + age + "\n")

    为你的输入循环试试这个:

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

    【讨论】:

    • 感谢您的评论。这对我非常有用。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多