【问题标题】:Writing, updating and reading lists to and from external files with user inputs使用用户输入在外部文件中写入、更新和读取列表
【发布时间】:2018-08-31 11:05:18
【问题描述】:

我查看了使用 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)

【问题讨论】:

  • 欢迎来到 SO。请参阅How to Askminimal reproducible example。此问题应包含样本输入数据和基于该样本的所需输出。您还可以展示您尝试过的内容以及遇到的问题。 SO 不是免费的代码编写服务。

标签: python python-3.x


【解决方案1】:

解决方案

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,而不仅仅是打印它。另外我会考虑把它变成一个ifelse循环并创建一些条件,比如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)

【讨论】:

  • 非常感谢,我可以在此基础上再接再厉!
  • @Y.Bayar 欢迎您。另外,我会推荐 Python Crash Course,它非常清楚地涵盖了这一点,以及许多其他主题。
猜你喜欢
  • 1970-01-01
  • 2017-06-18
  • 2023-03-13
  • 2017-03-11
  • 1970-01-01
  • 1970-01-01
  • 2015-07-26
  • 2013-06-17
相关资源
最近更新 更多