Skip to content Skip to sidebar Skip to footer

Writing Nicely Formatted Text In Python

In Python, I'm writing to a text file with code like: f.write(filename + type + size + modified) And of course the output looks really ugly: C:/Config/ControlSet/__db.006 file

Solution 1:

If you can get a list of all filenames first, then you could do something like:

max_width = max(len(filename) for filename in filenames)
for filename in filenames:
    f.write(filename.ljust(max_width+1)+..whatever else..)

If you can't get a list of all filenames first, then there's no way to make sure that everything will line up, because there's no way to know if you'll later get a file whose name is really long.

In a case like this, though, I would usually just assume that N columns is generally sufficient, for some N, in which case you can just do something like:

f.write('%-40s %6s %10s %2s\n' % (filename, type, size, modified))

Solution 2:

I think what you're looking for is the str.ljust() method and maybe str.rjust() too.

As it says in the docs, the original string is returned if it's too long, so you will never truncate away any data, but you would have to find out the longest lengths ahead of time in order to get really perfect formatting. I would suggest just using a reasonably large number for the values unless it has to be perfect.

Something like...

f.write(
    "{0} {1} {2} {3}".format(
        filename.ljust(max_filename),
        type.rjust(max_type),
        size.rjust(max_size),
        modified.rjust(max_modified)
        )
    )

would do the trick.

Post a Comment for "Writing Nicely Formatted Text In Python"