Hi all, hope you are well. Just a quick one here that you pythons will be able to answer in no time (I am new with python). What I am trying to do is read a text file and print only the first and last line of that file. Any ideas as to how I might go about this ? I have read the file so all i need to do is find a way of finding out which is first and last line, and then printing them. Thanks for your time.

ok ignore the above link - it is a search link which doesnt seem to work. Here is the solution that I have worked out:

def lab01():
    file = open('filename.txt','r')#specify file to open
    data = file.readlines() #read lines in file and put 
    #into LIST called data
    print "Last line = "
    print data[len(data)-1] #-1 represents last item on list data
    print "First line = "
    file.seek ( 0 )#seek to first line in file
    print file.readline()
    file.close() #good practice to close files after use

Restructured the code to make it a little more elegant now:

def lab01():
    file = open('swift20080428172404.txt','r')#specify file to open
    data = file.readlines() #read lines in file and put into 
    #LIST called data
    file.close() #good practice to close files after use
    print "Last line = "
    print data[len(data)-1] #-1 represents last item on list data
    print "First line = "
    print data[0] #-1 represents last item on list data
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.