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"

Recommended Answers

All 2 Replies

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
    file.close()

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

commented: Great help, swift and valid response ! +2

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]

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.