首页 > 解决方案 > 每当我尝试运行 EDIT 函数时,该函数都会执行,但文本不会附加到文件中

问题描述

 def EDIT():
    print("\nEnter the file you want to edit")
    command = input('\n$input<<')
    try:
        f = open(command + ".txt", "a")
        f.write(input('\n$append<<'))
    except FileNotFoundError:
        print('\nSorry, there was an error while trying to create your file. The file doesn\'t exist.\n')
    finally:
        NOTEPAD()
        

每当我尝试运行这行特定的代码时,程序就会运行,但是在检查文件时,没有任何变化

标签: pythonpython-3.x

解决方案


您需要关闭文件以刷新缓冲区。

通常最好使用上下文管理器,这样文件就会自动关闭。

def EDIT():
    print("\nEnter the file you want to edit")
    command = input('\n$input<<')
    try:
        with open(command + ".txt", "a") as f:
            f.write(input('\n$append<<'))
    except FileNotFoundError:
        print('\nSorry, there was an error while trying to create your file. The file doesn\'t exist.\n')
    finally:
        NOTEPAD()

推荐阅读