2017-07-30 92 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) 

適合我工作。

相關問題