python - 如何在 python 的文本文件中添加总数?

标签 python

我一直被困在total_num()函数中,因为它给出了错误

“ValueError:以 10 为基数的 int() 的文字无效:''”

如果它是一个已定义的列表,我知道该怎么做,但如果它是由用户设置的,我会感到困惑。

def total_num():
    total = 0
    num_file = open("num_list.txt", "r")
    line = num_file.read()

    while line != "":
        num1 = int(num_file.readline())

        total = total + num1

    print total


def read_num():
    num_file = open("num_list.txt", "r")

    for line in num_file:
        print line.rstrip("\n")

def write_num():
    num = input("Enter a number: ")
    num_file = open("num_list.txt", "w")
    num_consec = 0

    for x in range(num):
        num_consec = num_consec + 1
        num_file.write(str(num_consec)+ "\n")

    num_file.close()

def main():
    write_num()
    read_num()
    total_num()


main()

最佳答案

该错误是因为您从文本文件中获取了空字符串。看看这段代码;您正在将整个文件读入内存。

line = num_file.read()

while line != "":

在这里,除非您打开一个空文件line != "",否则您会将整个文件与空字符串进行比较。因此,您将继续循环,直到 num1 = int(num_file.readline()) 从文件中读取空行。

如果您查看 read_num 方法,您就可以找到解决方案。

for line in num_file:
    try:
        total += int(line)
    except ValueError:
        print "Invalid data in ", line

通过使用try except,您可以处理文件可能包含其他无效文本的情况。

关于python - 如何在 python 的文本文件中添加总数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37017092/

相关文章:

python - pyserial 错误 - 无法打开端口

python - 如何只在必要时导入模块并且只导入一次

python - Django:get_absolute_url 不起作用

python - 使用 python 字典插入到 mysql

python - 为什么一个频繁出现的词会被错误分类?

python - 在 PyMC 中设置随机变量的界限

python - mongoengine.connection.ConnectionError : Cannot connect to database default : [Errno 111] Connection refused

python - 在 hyperopt 中设置条件搜索空间的问题

Python - Pandas 描述抛出错误 : unhashable type 'dict'

python - SQLite 还是纯文本文件?