读取 python 中的文件,不跳过第一个数字

Reading a file in python, without skipping the first number

我需要在 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 添加到 amount 变量。但后来我再次测试并注意到它正在跳过文件中的第一个数字。

怎么样:

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。我添加了一个使用 try/except 捕获 ValueError 的示例,以防它遇到由于某种原因无法转换为数字的行。

这是我 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]

假设,在您生成这些数字的代码中,'random_numbers.txt' 的内容是由换行符分隔的整数:

with open('random_numbers.txt', 'r') as f:
    numbers = [int(line) for line in f.readlines()]
    total = sum(numbers)
    numOfNums = len(numbers)

'numbers' 包含列表中文件中的所有数字。如果您不想要方括号,可以打印这个或 print(','.join(map(str,numbers))) 。

'total'是他们的总和

'numOfNums' 是文件中有多少个数字。

最终对我有用的是:

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)

Cory 关于添加 try 和 except 的提示是我认为最终成功的方法。

如果是我,我想这样编码:

from random import randint

fname = 'random_numbers.txt'
amount = int(input('How many random numbers do you want in the file? '))
with open(fname, 'w') as f:
    f.write('\n'.join([str(randint(1, 500)) for _ in range(amount)]))

with open(fname) as f:
    s = f.read().strip()    
numbers = [int(i) for i in s.split('\n') if i.isdigit()]
print(numbers)

或者像这样(需要pip install numpy):

import numpy as np
from random import randint

fname = 'random_numbers.txt'
amount = int(input('How many random numbers do you want in the file? '))
np.array([randint(1, 500) for _ in range(amount)]).tofile(fname)

numbers = np.fromfile(fname, dtype='int').tolist()
print(numbers)

我认为问题在于您如何放置代码,因为您无意中跳过了第一行并再次调用 infile.readline()

amount = 0
total = 0
infile = open ('random_numbers.txt', 'r')
numbers = (infile.readline())
try:

    while numbers:
        numbers = numbers.strip('\n')
        numbers = int (numbers)
        print (numbers)
        total += numbers
        amount += 1
        numbers = (infile.readline())       #Move the callback here. 


except ValueError:
    raise ValueError
print ('')
print ('')
# The amount should be correct already, no need to increment by 1.
# amount +=1

print ('Your total is: ' ,total)
print ('The amount of numbers in file is: ', amount)

对我来说很好用。