Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing nicely formatted text in Python

Tags:

python

file

text

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          56 KB   2012-Apr-30 10:00:46.467 AM
C:/Config/ControlSet dir       68881 KB   2012-Apr-30 10:00:46.396 AM 
C:/Config/DataStore.avlocate file           0 KB   2012-Apr-30 09:57:42.440 AM 
C:/Config/DataStoreLocate.bak file           0 KB   2012-Apr-30 09:57:42.470 AM 
C:/Config/DeviceConnections/devconn.bak file          41 KB   2012-Apr-30 10:39:50.181 AM   
C:/Config/DeviceConnections/devconn.cfg file          41 KB   2012-May-29 10:12:45.288 AM

But I want to align the entries so it looks like this:

C:/Config/ControlSet/__db.006                                            file          56 KB   2012-Apr-30 10:00:46.467 AM
C:/Config/ControlSet                                                      dir       68881 KB   2012-Apr-30 10:00:46.396 AM 
C:/Config/DataStore.avlocate                                             file           0 KB   2012-Apr-30 09:57:42.440 AM 
C:/Config/DataStoreLocate.bak                                            file           0 KB   2012-Apr-30 09:57:42.470 AM 
C:/Config/DeviceConnections/devconn.bak                                  file          41 KB   2012-Apr-30 10:39:50.181 AM   
C:/Config/DeviceConnections/devconn.cfg                                  file          41 KB   2012-May-29 10:12:45.288 AM

My issue is similar to this question except I don't know how long the filenames will be beforehand. How should I approach this?

like image 289
Jeffrey Greenham Avatar asked May 30 '12 17:05

Jeffrey Greenham


People also ask

What does %d and %s do in Python?

They are used for formatting strings. %s acts a placeholder for a string while %d acts as a placeholder for a number. Their associated values are passed in via a tuple using the % operator.

What is %d %s %F in Python?

Answer. In Python, string formatters are essentially placeholders that let us pass in different values into some formatted string. The %d formatter is used to input decimal values, or whole numbers. If you provide a float value, it will convert it to a whole number, by truncating the values after the decimal point.

Can you format text in Python?

Python uses C-style string formatting to create new, formatted strings. The "%" operator is used to format a set of variables enclosed in a "tuple" (a fixed size list), together with a format string, which contains normal text together with "argument specifiers", special symbols like "%s" and "%d".


2 Answers

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))
like image 182
Edward Loper Avatar answered Oct 03 '22 12:10

Edward Loper


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.

like image 29
mayhewr Avatar answered Oct 03 '22 11:10

mayhewr