我需要用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。但後來我再次測試,發現它跳過了文件中的第一個數字。
這可能是因爲在文件寫入時在行尾添加了''\ n',現在在讀取時將''\ n''轉換爲'int',這是不可能的 – ksai
@ksai我很確定這是事實。我試圖從它中剝離\ n,無濟於事。 – Whitekong