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

时间:2017-07-30 03:43:59

标签: python readfile writefile

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

5 个答案:

答案 0 :(得分:2)

怎么样:

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]

答案 1 :(得分:0)

假设,与生成这些数字的代码一样,'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'包含列表中文件的所有数字。如果你不想要方括号,你可以打印或打印(','。join(map(str,numbers)))。

'total'是他们的总和

'numOfNums'是文件中的数字。

答案 2 :(得分:0)

最终为我工作的是:

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关于添加尝试的提示,除了我认为最终完成了这个技巧。

答案 3 :(得分:0)

如果我,我想这样编码:

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)

答案 4 :(得分:0)

我认为问题在于您如何放置代码,因为您无意中跳过第一行并再次调用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)

对我来说很好。