Hey there.
i want to set a variable to represent the last line of a text file
how do i do that?
or even better, how do i create a list of the lines of a text file?
any suggestions?

Use readlines() to get a list of lines ...

# read a text file as a list of lines
# find the last line, change to a file you have
fileHandle = open ( 'test3.txt',"r" )
lineList = fileHandle.readlines()
fileHandle.close()
print lineList
print "The last line is:"
print lineList[len(lineList)-1]
# or simply
print lineList[-1]

Great !
Works great.
You know, you are the one who helped me with my last problem.
thanks a whole lot.
you are making my life easier.
:cheesy:

Use readlines() to get a list of lines ...

# read a text file as a list of lines
# find the last line, change to a file you have
fileHandle = open ( 'test3.txt',"r" )
lineList = fileHandle.readlines()
fileHandle.close()
print lineList
print "The last line is:"
print lineList[len(lineList)-1]
# or simply
print lineList[-1]

what has fileHandle been replaced with in python 3.1 as it does not reconise it as a module or a function?
THANKS
dan holding

Everything should work as long as you replace the print command with print function, manually or by 2to3.

More shortly:

# find the last line, change to a file you have
with open('test.txt') as myfile:
    print (list(myfile)[-1])

Edited 5 Years Ago by pyTony: n/a

Comments
very helpfull

what has fileHandle been replaced with in python 3.1

FileHandle is just a variable name used by vega.
You can use whatever name you want.
Here is the same code for python 3

# Testet work for python 3
# read a text file as a list of lines
# find the last line, change to a file you have
fileHandle = open ('test3.txt')
lineList = fileHandle.readlines()
fileHandle.close()
print (lineList)
print ("The last line is:")
print (lineList[len(lineList)-1])
# or simply
print (lineList[-1])

Or if we use an other name than FileHandle just f

# Testet work for python 3
# read a text file as a list of lines
# find the last line, change to a file you have
f = open ('test3.txt')
lineList = f.readlines()
f.close()
print (lineList)
print ("The last line is:")
print (lineList[len(lineList)-1])
# or simply
print (lineList[-1])

Postet over is a more modern solution by tony.
with open() close the file object auto,so no need for close()

Edited 5 Years Ago by snippsat: n/a

Comments
very helpfull

If you have question dont use a 6 year old post that has been marked solved.
Make a new post,just copy some code from older post if you have question about it.

Edited 5 Years Ago by snippsat: n/a

i usually do i just happened to see this post and though i would just find out what File handler was as had never heard of it.

This question has already been answered. Start a new discussion instead.