python - 使用用户输入在外部文件中写入、更新和读取列表
问题描述
我查看了使用 csv、txt、py 文件的各种解决方案,但无法完成我想要的,即:
- 我想将整数列表保存在单独的文件中
- 通过用户输入将新条目附加到该单独文件的列表中
- 并以 int 形式将更新版本作为列表读回,以便可以从该文件中进行计算。
我一直在尝试以下代码;
print('Enter the result of your last reading=')
newReading = input()
reading = [int(newReading)]
with open('avg.py', 'a') as f:
f.write('reading = ' . reading)
from avg.py import reading as my_list
print(my_list)
解决方案
解决方案
filename = "avg.txt"
while True:
new_reading = input("\nEnter the result of your last reading: ")
with open(filename, 'a') as f_obj:
f_obj.write(new_reading)
with open(filename) as f_obj:
contents = f_obj.read()
reading = list(contents)
print(reading)
输出
(xenial)vash@localhost:~/python$ python3 read_write_files.py Enter the result of your last reading: 1 ['1'] Enter the result of your last reading: 2 ['1', '2'] Enter the result of your last reading: 3 ['1', '2', '3']
注释
这条路线涉及使用第二段代码打开文件,然后我读取数据并将其存储到contents
. 之后可以使用 将内容转换为列表list(contents)
。
您可以从这里处理列表reading
,而不仅仅是打印它。另外我会考虑把它变成一个if
else
循环并创建一些类似的条件q to quit
来结束程序。
像这样的东西:
filename = "avg.txt"
while True:
new_reading = input("\nEnter the result of your last reading" \
"('q' to quit): ")
if new_reading == "q":
break
else:
with open(filename, 'a') as f_obj:
f_obj.write(new_reading)
with open(filename) as f_obj:
contents = f_obj.read()
reading = list(contents)
print(reading)
推荐阅读
- c# - protogen:创建cs文件
- c - 文件结束(EOF)是在文本结束之后还是取决于编译器?
- typescript - 属性“提交”不存在
- python - python为什么我不能在将它附加到for循环后清除列表而不保持清除
- angular - 从 DB 通过 HTML 传递 Angular 自定义组件
- typescript - 解构时类型推断丢失
- reactjs - Redux如何设置初始状态
- c++ - std::packaged_task 是如何复制我的转发参考参数的?
- flutter - 具有省略号功能的 Flutter Wrap 小部件
- swift - 无法调用非函数类型“ViewRouter”的值