【问题标题】:How do i change this so when i run the functions it adds to my .txt file?当我运行它添加到我的 .txt 文件中的函数时,我该如何更改它?
【发布时间】:2021-10-21 10:13:53
【问题描述】:

我应该创建一个函数来将名称和数字添加到 a.txt 文件中,以及一个用于读取文件的函数。我做错了什么,我该如何纠正?第一次发帖,不知道是不是格式不对,抱歉。

def add():
    while True:
        name = input("Name and number: ")
        with open("Telefon.txt", "a") as f:
            f.write(name)
        f.close()
        if name == "Enter":
            break
        
def read():        
    f = open("Telefon.txt", "r")
    print(f.read)

【问题讨论】:

    标签: python function file-handling


    【解决方案1】:

    您的代码中存在某些逻辑和优化错误,您不应该一次又一次地打开文件并在循环中关闭它,也可以使用空条件来终止循环,例如按回车而不输入任何东西。为了阅读,我用 redlines 方法替换了你的 read 方法

    def add():
        with open("Telefon.txt", "a") as f:
            while True:
                name = input("Name and number: ")
                f.write(name + '\n')
                if name == "":
                    break
            
    def read():        
        f = open("Telefon.txt", "r")
        print("".join(f.readlines()))
    
    add()
    read()
    

    输出如下

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-07
      相关资源
      最近更新 更多