我需要用 Python 编写一个程序,它查看单独文本文件中的数字列表,并执行以下操作:显示文件中的所有数字,将所有数字相加,告诉我有多少个数字在文件中。我的问题是它跳过文件中的第一个数字
这是写入文件的程序的代码,如果有帮助的话:
import random
amount = int (input ('How many random numbers do you want in the file? '))
infile = open ('random_numbers.txt', 'w')
for x in range (amount):
numbers = random.randint (1, 500)
infile.write (str (numbers) + '\n')
infile.close()
这是我读取文件中数字的代码:
amount = 0
total = 0
infile = open ('random_numbers.txt', 'r')
numbers = (infile.readline())
try:
while numbers:
numbers = (infile.readline())
numbers = numbers.strip('\n')
numbers = int (numbers)
print (numbers)
total += numbers
amount += 1
except ValueError:
pass
print ('')
print ('')
amount +=1
print ('Your total is: ' ,total)
print ('The amount of numbers in file is: ', amount)
现在我的问题是它跳过了文件中的第一个数字。我首先注意到它没有给我正确数量的数字,因此附加语句将额外的 1 添加到数量变量。但是后来我再次测试并注意到它跳过了文件中的第一个数字。
怎么样:
with open('random_numbers.txt', 'r') as f:
numbers = map(lambda x: int(x.rstrip()), f.readlines())
这将从字符串中的行中去除任何尾随换行符,然后将其转换为 int。完成后,它还会关闭文件。
我不确定你为什么要计算它循环的次数,但如果这是你想要做的,你可以这样做:
numbers = list()
with open('random_numbers.txt', 'r') as f:
counter = 0
for line in f.readlines():
try:
numbers.append(int(line.rstrip()))
except ValueError: # Just in case line can't be converted to int
pass
counter += 1
不过,我只会使用len(numbers)
第一种方法的结果。
正如 ksai 所提到的ValueError
,最有可能的是,因为\n
在行的末尾。我添加了一个示例,用于捕获 ValueErrortry/except
以防万一它遇到由于某种原因无法转换为数字的行。
这是在我的 shell 中成功运行的代码:
In [48]: import random
...:
...: amount = int (input ('How many random numbers do you want in the file?
...: '))
...: infile = open ('random_numbers.txt', 'w')
...: for x in range (amount):
...: numbers = random.randint (1, 500)
...: infile.write (str (numbers) + '\n')
...: infile.close()
...:
How many random numbers do you want in the file? 5
In [49]: with open('random_numbers.txt', 'r') as f:
...: numbers = f.readlines()
...: numbers = map(lambda x: int(x.rstrip()), numbers)
...:
In [50]: numbers
Out[50]: <map at 0x7f65f996b4e0>
In [51]: list(numbers)
Out[51]: [390, 363, 117, 441, 323]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句