使用用户输入编写,更新和读取外部文件的列表

问题描述 投票:-3回答:1

我使用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)
python python-3.x
1个回答
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)
© www.soinside.com 2019 - 2024. All rights reserved.