如何将输出中的文本与文件对齐

问题描述 投票:0回答:1

我找到了许多关于如何以多种样式/格式等进行打印的解决方案,但我需要知道如何在文件中进行打印。

我有下面的代码......

import glob
import getpass
user = getpass.getuser()

import time

timestr = time.strftime("%Y%m%d-%H%M%S")
read_files = glob.glob("myOrders/*.txt")

with open("myOrderCopies/" +user+ "_" +timestr+ "_Hard_Drive_Order.txt", "wb") as outfile:
    for f in read_files:
        with open(f, "rb") as infile:
            outfile.write(infile.read())

# Read .txt file and putlines row_name and Product ID into new .txt file
searchquery = 'row_name', 'Product ID'

#source file
with open("myOrderCopies/" +user+ "_" +timestr+ "_Hard_Drive_Order.txt") as f1:
    #output file
    with open("hwOrderCopies/" +user+ "_" +timestr+ "_HardDriveSummary.txt", "wt") as f2:
        lines = f1.readlines()
        for i, line in enumerate(lines):
            if line.startswith(searchquery):
                f2.write("\n" + line)
                #f2.write(lines[i + 1])
                #f2.write(lines[i + 2])

#count how many occurances of 'Product ID'
import os

#def main():
with open("hwOrderCopies/" +user+ "_" +timestr+ "_HardDriveSummary.txt", "a+") as f:
    term = "Product ID"
    count = f.read().count(term)
    f.seek(os.SEEK_END)  # Because we've already read the entire file. Go to the end before writing otherwise we get an IOError
    f.write("\nTotal Number of Hard Drives: "+str(count)+ "\n\n")

它可以在文件中获得我想要的东西。问题在于对齐(下图)。如何让row_name的结果在右边对齐?

row_name        California Datacenter

Product ID                      : ST3600057SS

Product ID                      : ST3600057SS

Total Number of Hard Drives: 2
python format output
1个回答
2
投票

使用列表来说明使用format()来对齐项目,解决问题的方法如下:

row_item = ['row_name', 'California Datacenter']
output = '{}{:>40}'.format(row_item[0], row_item[1])

print(output)

输出:

row_name                   California Datacenter

'{}'出现代表format(variable_1, variable_2)示例中的单个变量。

第二个元素({:>40})中的语法表示使用:>进行右对齐。 :<将保持一致。 40指定输出字段的宽度将填充为40个字符。

这是一个稍微优化的代码版本,它应该产生你想要的输出,重命名的变量更易读(总是一个好习惯),格式化可用作变量。如上所述,formatting字符串中的数字决定了填充的宽度。调整将使列更近或更远。请注意,我冒昧地格式化Product ID行以及row_name

为了便于阅读,我还将文件名抽象为变量,并将第二组嵌套的with open()语句移动到复合with上下文管理器中,因为它们在循环中不会发生变化。

import glob
import os
import time
import getpass

user = getpass.getuser()

timestr = time.strftime("%Y%m%d-%H%M%S")
read_files = glob.glob("myOrders/*.txt")
myOrderCopies_file = "myOrderCopies/" + user + "_" + timestr + "_Hard_Drive_Order.txt"
hwOrderCopies_file = "hwOrderCopies/" + user + "_" + timestr + "_HardDriveSummary.txt"

searchquery = 'row_name', 'Product ID'
term = "Product ID"

formatting = '{:<40}{:>}\n\n'

# Read .txt files and put lines 'row_name' and 'Product ID' into new .txt file
with open(myOrderCopies_file, "wb") as myOrderCopies:
    for file_name in read_files:
        with open(file_name, "rb") as infile:
            myOrderCopies.write(infile.read())

with open(myOrderCopies_file, 'rb') as myOrderCopies, open(hwOrderCopies_file, "w") as hwOrderCopies:
    term_counter = 0
    lines = myOrderCopies.readlines()
    for line in lines:
        if line.startswith(searchquery):
            if "row_name" in line:
                split_line = line.split('        ')
            else:
                if term in line:
                    term_counter += 1
                split_line = line.split('                      : ')
            hwOrderCopies.write(formatting.format(split_line[0], split_line[1]))
    hwOrderCopies.write("\nTotal Number of Hard Drives: {}\n\n".format(str(term_counter)))
© www.soinside.com 2019 - 2024. All rights reserved.