Writing beautifully formatted text in Python

In Python, I write a text file with code like:

f.write(filename + type + size + modified) 

And, of course, the output looks very 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 that they look 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 problem is similar to this question , except that I do not know how long the file names will be in advance. How do I approach this?

+6
source share
2 answers

If you can get a list of all the file names first, you can 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 cannot get a list of all the file names at the beginning, then there is no way to make sure everything is lined up because there is no way to find out if you will later receive a file whose name is really long.

In this case, as usual, I usually assumed that N columns are usually enough for some N, and in this case you can just do something like:

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

I think you are looking for the str.ljust () method and maybe str.rjust () too.

As the docs say, the original string is returned if it is too long, so you never truncate any data, but you will need to find the longest lengths ahead of time in order to get really great formatting. I would suggest just using a sufficiently large number for the values ​​if it should not be ideal.

Sort of...

 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.

+10
source

Source: https://habr.com/ru/post/917034/


All Articles