0

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.

Dhruv_2676
  • 101
  • 1
  • 9

2 Answers2

2

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('./')

Aven Desta
  • 2,114
  • 12
  • 27
  • Hello Aven, Can You Explain how `{: >30} {: >30}` This Works! I Didn't Understand how it works!? – Dhruv_2676 Feb 18 '21 at 11:07
  • [HERE](https://stackoverflow.com/questions/8450472/how-to-print-a-string-at-a-fixed-width) for more – Aven Desta Feb 18 '21 at 11:07
  • 1
    `{: 30}` reserves 30 characters for the print output. If the printed word is less than 30, it will fill it with empty space, to make it 30 characters long – Aven Desta Feb 18 '21 at 11:08
1

The easiest most straightforward way is to use tabulate.
The package lets you output data into tables through the standard output stream

Usage Example:

>>> table = [["spam",42],["eggs",451],["bacon",0]]
>>> headers = ["item", "qty"]
>>> print(tabulate(table, headers, tablefmt="plain"))
item      qty
spam       42
eggs      451
bacon       0

There are plenty of output options in this package. Just go and see it yourself :)

Omer
  • 102
  • 1
  • 10
  • Yes, This Is a Perfectly Correct Answer But I Don't want to save the name and size in nested lists but print while the program is analyzing the file for its size! – Dhruv_2676 Feb 18 '21 at 11:03