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.

Dani AI

Generated

Nice progress. One caution: readlines() loads the entire file into memory, which can bite you on large inputs. A streaming approach grabs the first line right away and remembers only the last line while you iterate. The simplest pattern is to pair next() with a bounded collections.deque(maxlen=1). See the deque docs for why this is both simple and memory-friendly. collections.deque. (docs.python.org)

from collections import deque

def print_first_and_last(path):
    with open(path, 'r', encoding='utf-8', errors='replace') as f:
        first = next(f, '')
        if first == '':
            print('File is empty')
            return
        last_buf = deque(f, maxlen=1)     # keep only the most recent line
        last = last_buf[0] if last_buf else first
    print('First line =')
    print(first.rstrip('\r\n'))
    print('Last line =')
    print(last.rstrip('\r\n'))

Why this works:

Tip: avoid naming a variable file (especially in old Python 2 code) to prevent confusion with the historical built-in.

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.