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"

Dani AI

Generated

Nice, concise fix from — slicing each line is the right idea, and ’s follow-up shows it works. A few practical improvements make the solution more robust and easier to reuse: stream the file instead of calling readlines(), use a context manager so the file is always closed, strip trailing newlines before counting characters, and handle Unicode/encoding safely.

# Python 3 — stream file, show line numbers, add "..." when truncated
def print_first_n(path, n=15):
    with open(path, 'r', encoding='utf-8', errors='replace') as fh:
        for lineno, raw in enumerate(fh, 1):
            line = raw.rstrip('\r\n')
            snippet = line if len(line) <= n else line[:n] + '...'
            print("{:4d}: {}".format(lineno, snippet))

This avoids building a full list in memory (so it scales for large files), and rstrip keeps the visible text length correct. The errors='replace' prevents crashes on malformed bytes; adjust or remove it if strict decoding is required. For Python 2, open via codecs.open(..., 'r', 'utf-8') or decode each line to unicode before slicing, and either use from __future__ import print_function or the old print style.

Additional notes: if only the last line is needed (instead of printing all first-15 snippets), don’t use readlines() — use collections.deque(fileobj, maxlen=1) to capture the tail efficiently. For quick shell alternatives, cut -c1-15 filename or awk '{print substr($0,1,15)}' filename work well. Be aware that slicing counts code points (Python 3 strings); grapheme clusters or combining marks can be split in the middle if exact visual characters matter.

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.