【问题标题】:How to add numbers in an array stored in a file python如何在存储在文件python中的数组中添加数字
【发布时间】:2018-02-02 11:11:49
【问题描述】:

所以我试图添加存储在文件中的变量中存储的数字。

if rw == "s":
    fo = open("foo.txt", "w")
    while int(count) != 0:
        x = input("Input a number for storage ")
        count = int(count) - 1
        test.append(int(x))
        print("")
    fo.write("%s" % test)
    fo.close()

fo = open("foo.txt", "r")
add = int(fo.readlines(1)) + int(fo.readlines(2))

我不太明白最后一部分是如何工作的。我得到的错误如下:

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

文件的内容如下所示: [6, 7, 8, 9, 5, 4, 3]

任何帮助将不胜感激

【问题讨论】:

    标签: arrays python-3.x file


    【解决方案1】:

    如果您想选择列表的第一个和第二个值并将它们相加,请执行此操作

    content = fo.readlines(1)
    content = content[0].replace('[', '').replace(']', '')
    numbers = content.split(", ")
    add = int(numbers[0]) + int(numbers[1])
    

    解释:

    readlines 读取文件中的所有行并返回一个列表。 readlines(index) 将返回一个仅包含所选行的列表。无论哪种情况,您都不能调用int()

    【讨论】:

    • 我明白了,它奏效了。如果我想添加其他数字,是否需要更改 content
    • 数字数组将包含您以字符串格式添加的所有数字。您可以对其进行索引以获取其中任何一个,但不要忘记将其转换为 int
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多