如何在 Python 中在美观的列中打印单独的字符串?

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

我做了一个Python脚本,它接受一个字符串directory_path,然后通过os.listdir(directory_path)列出目录的内容,然后进入for循环,然后打印名称文件和文件的大小。

这是我的代码:

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"))

但是上面的代码以这种方式给出了输出:

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

我希望它在两列中正确,这里 - 如果文件名的大小相同,那么它会正确地给我两列,否则它是不均匀的。

据此Whosebug Question!我们需要从列表中按列打印它。但是,我不想在列表中保存文件的名称和大小然后打印它!我希望它在分析文件大小时打印出来!

请给我一个解决方案。

最简单最直接的方法是使用tabulate
该包允许您通过标准输出流将数据输出到表中

用法示例:

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

这个包中有很多输出选项。自己去看看吧:)

修复打印函数中第一列的宽度。目前您只对第二列执行此操作。

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