Python TextFile Class

You know what I mean: those ***** little things where you need to strip comments (as long as # is your comment character), skip blank lines, join adjacent lines by escaping the newline (ie. backslash at end of line), and strip leading and/or trailing whitespace.

But don’t freak out! The TextFile class has got your back. It’s like having a personal assistant who takes care of all those annoying tasks for you. And best of all, it’s optional so if you don’t need any of that fancy functionality, just ignore this tutorial and go about your merry way!

But let’s say you do want to use the TextFile class. How do you create an instance? Well, there are a few ways: either with filename, file, or both (depending on how lazy/lazy-ish you feel). Here’s some code that demonstrates all three options:

# Option 1: Using just the filename
# Open the file 'example.txt' in read mode and assign it to the variable 'f'
with open('example.txt', 'r') as f:
    # Create an instance of the TextFile class, passing in the file object 'f'
    text_file = TextFile(f)
    
# Option 2: Using both filename and file object
# Open the file 'example.txt' in read mode and assign it to the variable 'f'
# Then, create an instance of the TextFile class, passing in the filename and the file object 'f'
text_file = TextFile('example.txt', file=open('example.txt', 'r'))
    
# Option 3: Using just the file object (if you already have it open for some reason)
# Open the file 'example.txt' in read mode and assign it to the variable 'f'
with open('example.txt') as f:
    # Create an instance of the TextFile class, passing in the file object 'f' and specifying the mode as 'r'
    text_file = TextFile(f, mode='r')

And that’s really all there is to it! The TextFile class provides a warn() method so you can generate warning messages that report physical line number, even if the logical line in question spans multiple physical lines. It also provides unreadline() for implementing line-at-a-time lookahead (which we won’t go into here because it’s not really relevant to this tutorial).

The Python TextFile class your new best friend when dealing with text files that have some line-by-line syntax.

SICORPS