繁体   English   中英

在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。 但是后来我再次测试,发现它正在跳过文件中的第一个数字。

怎么样:

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所述,很有可能由于行尾\\n出现ValueError 我添加了一个使用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)

“数字”包含列表中文件中的所有数字。 如果不希望使用方括号,则可以打印或打印(','。join(map(str,numbers))))。

“总计”是他们的总和

“ 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关于增加尝试的技巧,但我相信最终会成功。

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

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)

对我来说很好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM