RonB7
RonB7

Reputation: 297

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']

Upvotes: 1

Views: 445

Answers (4)

ifma
ifma

Reputation: 3818

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.

Upvotes: 2

joel goldstick
joel goldstick

Reputation: 4493

Change this:

while (len(myLine)>0) :
     strings = myLine[:-1]
     listofStr.append(strings)
     myLine = f.readline()

to this:

while myLine.strip() :
     strings = myLine.strip()
     listofStr.append(strings)
     myLine = f.readline()

Upvotes: 1

holdenweb
holdenweb

Reputation: 37043

You are missing the final newline on your file, so the strings = myLine[:-1] removes the final character. If you replace this with strings = myLine.rstrip() that will remove any trailing whitespace on the line but won't remove that final character.

Upvotes: 1

Marc B
Marc B

Reputation: 360702

The last line doesn't have a linebreak in it, so when you do

     strings = myLine[:-1]

you strip off the last char in the line, no matter what it is, and you kill off an actual character.

Upvotes: 1

Related Questions