在Python中我試圖從存儲在txt中的信息設置一個變量。我可以設置它,但它不能作爲一個數字。它被存儲爲別的東西嗎? 這裏是我的.txt文件(所有的信息被寫在一行,沒有\ NS):如何使用Python從文本文件中獲取整數?
11 14 15 3
這裏是我的腳本:
def break_words(text):
words = text.split(' ')
return words
file_name = open("set_initial.txt")
words = break_words(file_name.read())
shift_l1 = words[0]
shift_l2 = words[1]
shift_l3 = words[2]
shift_l4 = words[3]
shift_l5 = words[4]
shift_l6 = words[5]
# this part is to verify that the variables are being set:
print shift_l1, shift_l2, shift_l3, shift_l4
while shift_l4 < 28:
# and the script goes on into a loop from here
我使用這種方法,因爲的長度txt中的值將會改變(例如:114 34 2 4318)。當我運行腳本時,print函數工作正常,並返回我的變量作爲我的.txt中的數字(分別爲11 14 15 3),所以shift_l4打印爲3,所以我的WHILE循環應該正常工作。但事實並非如此。正如我所說,我認爲我的變量沒有被設置爲.txt中數字的數字值,但可能只是文本值?我不知道如何解決它。任何幫助或想法?
謝謝
好吧,我在這方面做了一些小小的閱讀,但看起來更合理,謝謝。腳本實際上轉到了shift_l8,並且在txt中有12組數字,但爲了簡化起見,我忽略了它。可惜我忘了省略shift_l5&shift_l6,所以我失敗了,哈哈。感謝您提供名稱提示。 – Gronk
@ user1042034您還應該選擇一個答案並關閉它,這將有助於您下次回答您的問題。 –