alphasapphire
alphasapphire

Reputation: 11

Get the last character of a String from a file in Python?

I'm trying to write a function that takes a character and places all words in ifile that ends with the character c into another new file. I thought this would based on string indexing, but the text file result is always blank. Why is it that line[0] will work but line[-1] won't? I don't understand why the same concept doesn't apply.

def getListEnd(c,ifile,ofile):
    for line in ifile:
        if c in line[-1]:
            ofile.write(str(line))

Upvotes: 1

Views: 255

Answers (1)

Oliver W.
Oliver W.

Reputation: 13459

Make sure to call ofile.close() in the same scope as where you wrote ofile = open('some_file.txt', 'w'), but after your call to getListEnd of course.

So you'll have your code looking like this:

def getListEnd(c,ifile,ofile):
    for line in ifile:
        if c in line[-1]:
            ofile.write(str(line))

infile = open('inputfile.txt', 'r')
outfile = open('outputfile.txt', 'w')
getListEnd('$', infile, outfile)
outfile.close()
infile.close()

If you don't call close(), your buffers might not get flushed correctly and thus your file won't be written to.

Upvotes: 1

Related Questions