我查看了使用csv,txt,py文件的各种解决方案,但不能完全实现我想要的功能,即:
我一直在尝试以下代码;
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)
答案 0 :(得分:0)
解决方案
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)