python - 保存输入并在重新启动程序时要求再次使用它
问题描述
如何保存用户的输入并在重新启动程序时询问他们是否要再次使用它,这样他们每次关闭程序时都不必输入相同的内容?
解决方案
你可以使用这样的东西。它将用户输入数据保存到config.py
模块中,因此您可以在任何地方使用它。
import os
user_input = None
if os.path.exists('config.py'): #check if config file exist
ask = input("Do you want use previous data? (yes/no)")
if ask == 'no':
user_input = input("Some things...")
elif ask == 'yes':
import config
user_input = config.last_input # take last value of input from config file
else:
print("Wrong command, please anserw yes or no.")
else:
user_input = input("Some things...")
print(user_input)
# save input
with open("config.py", "w+") as file:
file.write(f"last_input = {user_input}")
这是一种简单的方法,不需要使用 json 或 ini 文件。你可以复制粘贴这个,就可以了。
推荐阅读
- javascript - Javascript通过对象搜索电话数据并显示在表格中
- php - 从 localhost 调用 Google API
- javascript - 标签之间的 CSS 样式空间
- php - 在 Windows 7 上安装 PEAR
- angular - 如何为动态添加的新输入行设置 ngModel 角度 4+(mat-table)
- ansible - Ansible 拆分返回多个索引
- excel - 单击事件不适用于以编程方式/动态创建的选项按钮
- android - 只选择一个复选框;回收站视图;科特林
- flutter - 颤振医生 - 系统找不到指定的路径[不是重复的]
- python - 有什么方法可以在不写入本地磁盘的情况下将 xlsxwriter 生成的文件发送到 azure 数据湖?