我正在編寫採用.txt文檔的代碼,並在字符串列表中的每個.txt文件行上存儲每個單詞。然而,我的代碼決定它想要刪除最後一個字符串的最後一個字母,因爲一些隨機的原因,誰能告訴我爲什麼?從文件讀取刪除文檔中最後一個字符串的最後一個字母?
我的代碼:
import sys
listofStr = []
print (" ")
fname = input("Please enter file name: ")
print (" ")
try :
f = open(fname)
myLine = f.readline()
tuplist = []
while (len(myLine)>0) :
strings = myLine[:-1]
listofStr.append(strings)
myLine = f.readline()
f.close()
except IOError as e :
print("Problem opening file (Remember the file extension '.txt')")
sys.exit()
print(listofStr)
當跑:
Please enter file name: test.txt
['TEST', 'WAS', 'VERY', 'SUCCESSFU']
預期結果:
['TEST','WAS','VERY','SUCCESSFUL']