Hi all - hope you are well. I am trying to print out only the first 15 characters of each line of a text file. The trouble is I am not sure how I would go about doing such a thing! Any help will be greatly appreciated. Thank you for your time!

def lab01():
    file = open('blah.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 = "
    tail = data[len(data)-1]#-1 represents last item on list data, load this into VAR tail
    print tail
    print "First line = "
    header = data[0]#0 represents first item on list data, load this into VAR header
    print header
    del data[0]
    print "first line removed from LIST data, second line is now first "
    #~ print data[0] # will print out line 2 (now line 1) because line 1 had been removed
    #from list data.
    del data[len(data)-1]
    print "Final line removed from LIST data, penultimate line is now final"
10 Years
Discussion Span
Last Post by majestic0110

Start with this, off the cuff:

file = open('blah.txt','r')#specify file to open
    for line in file: # Do the following for every line in the file, one at a time
        print line[0:15]  # Slice off the first 15 characters

Doesn't quite do what you want, but close enough to work from.

Votes + Comments
Great help, swift and valid response !

OK BearofNH, Many thanks for the response. I have modified your answer slightly and it works a treat. Great help - thanks!

for line in data:
print line[0:15]

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.