Python builtins.ValueError

时间:2015-08-18 04:25:44

标签: python integer

我正在编写一个程序,以写入模式打开numbers.txt文件,并提示用户指定要在其中存储的数量。然后该号码将存储在文件中。这就是我遇到问题的地方,每当我到达3(1,2,3)时ValueError: invalid literal for int() with base 10:,

以下是代码:

f = open("numbers.txt", "w")
n = int(input("How many numbers? "))
print("Enter", n, "number")
for i in range(0, n):
    m = input()
    f.write("%s\n" %m)
f.close()
f = open("numbers.txt")
lines = f.readline()
f.close()
print("The numbers stored in the file are")

for line in lines:
   print(int(line))

print("The numbers in the file multiplied by 2")
for line in lines:
   print (int(line)*2)

1 个答案:

答案 0 :(得分:0)

lines = f.readline()

从文件中读取一行行,将其存储为单个字符串。

for line in lines:

因此,一次迭代该字符串一个字符

第一次循环时,它会获得'3',下次获取'\n'(换行符)。

    print(int(line))

换行符本身无法转换为int