Search code examples
pythonpython-3.xpython-os

How To Print Separate Strings In Good Looking Columns In Python?


I Made A Python Script Which Takes A String directory_path and then lists the contents of the directory through os.listdir(directory_path) then goes into a for loop and then prints the Name of the File and The Size of the File.

Here's My Code:

import os

def print_size(directory_path):
    all_files_in_directory = os.listdir(directory_path)
    for file in all_files_in_directory:
        print("{} {: >30}".format(file, str(int(os.path.getsize(directory_path + file) / 1024)) + " KB"))

But The Code Above gives output in this manner:

IMG_14-03-2019_175157.jpg                         508 KB
IMG_14-03-2019_175202.jpg                         555 KB
IMG_14-03-2019_221148_HHT.jpg                         347 KB
IMG_14-03-2019_221156_HHT.jpg                         357 KB

I Want it correctly in two columns, Here - If the file name's size is the same then it gives me correctly two columns, or else it is uneven.

According To This StackOverFlow Question! We Need To Print It In Columns From Lists. But, I Don't want to save the name and size of the file in lists and then print it! I want it to be printed when it analyzes the file for the size!

Please Give Me A Solution To This.


Solution

  • Fix the width for the first column in the print function. Currently you're only doing that for the second column.

    import os
    
    def print_size(directory_path):
        all_files_in_directory = os.listdir(directory_path)
        for file in all_files_in_directory:
            print("{: >30} {: >10}".format(file, str(int(os.path.getsize(directory_path + file) / 1024)) + " KB"))
    
    print_size('./')