RJB RJB - 6 months ago 28
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]

myLine = f.readline()


except IOError as e :
print("Problem opening file (Remember the file extension '.txt')")


when ran:

Please enter file name: test.txt


expected outcome:



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.