RJB RJB - 4 months ago 10
Python Question

Reading from a file deletes the last letter of the last string in the document?

I am writing code which take a .txt doc and stores each word on each line of that .txt file in a list of strings. However my code decides it wants to delete the last letter of the last string for some random reason, can anyone tell me why?

My code:

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)


when ran:

Please enter file name: test.txt

['TEST', 'WAS', 'VERY', 'SUCCESSFU']


expected outcome:

['TEST','WAS','VERY','SUCCESSFUL']

Answer

You're slicing the last line which doesn't have the newline character:

strings = myLine[:-1]

To fix this you can just manually go to your file and append an extra line. Or change said line to strings = myLine.strip(). There is no need to slice the string manually since strip will handle whitespace and newlines.

Comments