python - 每当我尝试运行 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()
每当我尝试运行这行特定的代码时,程序就会运行,但是在检查文件时,没有任何变化
解决方案
您需要关闭文件以刷新缓冲区。
通常最好使用上下文管理器,这样文件就会自动关闭。
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()
推荐阅读
- javascript - 如果值大于0,如何更改表格数据颜色
- django - 根据发出请求的域过滤查询集
- permissions - 通过 Sublime 在 linux 上编辑 perl 文件需要什么权限
- mysql - MYSQL SELECT CASE 与 SUM 和 MAX
- arrays - 将可能的最小正整数插入唯一整数数组
- apache-nifi - 如何在 Nifi 的 RouteOnAttribute 中创建这样的验证 $ {param1 }> ${param2}
- swift - 使用 client.fetchArray 时出现内容错误
- php - 如何通过用户输入在 php 中组合产品变体
- jquery - 用于显示由 PHP 提供的图像的 jQuery 代码,无需重新加载
- solr - 如何在 Solr 中存储嵌套的关系数据