2017-07-30 93 views
0

我需要用Python编写一个程序,它查看单独文本文件中的数字列表,并执行以下操作:显示文件中的所有数字,添加所有数字的总数,告诉我文件中有多少个数字。 我的问题是,它跳过文件中的第一个数字在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。但后来我再次测试,发现它跳过了文件中的第一个数字。

+0

这可能是因为在文件写入时在行尾添加了''\ n',现在在读取时将''\ n''转换为'int',这是不可能的 – ksai

+0

@ksai我很确定这是事实。我试图从它中剥离\ n,无济于事。 – Whitekong

回答

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,以防万一遇到由于某种原因不能转换为数字的行。

下面的代码在我的壳成功运行:

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] 
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)))。

“总”是它们的总和

“numOfNums”是有多少个数字是在文件中。

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) 

科里的尖上添加一个尝试,除非是什么,我相信落得这样做的伎俩。

+0

没关系,现在它有一个跳过文件第一个数字的问题 – Whitekong

+0

它跳过第一个数字,因为你立即覆盖它在'while'语句的第一行。我也会把'try/except'放在while循环中,这样它就不会停在第一个坏行上。 –

+0

我该如何解决它? – Whitekong

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) 
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) 

适合我工作。

相关问题