繁体   English   中英

Python:写入文件时对齐 output(不打印)

[英]Python: Align output when writing to a file (not print)

我正在编写一个程序来分析博客。 我将各种结果放入一个名为“输出”的变量中,并将末尾的 output 写入文本文件。 下面只是一个例子:

output += "\nFiles and how many times they have been accessed: \n"
for key in accessedFiles.keys():
     output += key + "-> time(s) accessed is: " + "\t" + str(accessedFiles[key]) + " \n"

output 看起来像这样:

/paperarticles/Nov02-Bushswar.htm-> time(s) accessed is:    1 
/Documents/NinaSimone.htm-> time(s) accessed is:    1 
/cwi.css-> time(s) accessed is:     1

有类似的问题涉及到 print 命令。 我想出了这将如何与f-string一起使用,但我没有在我的代码中使用 print。 此外, "\t"不起作用,因为字符串的长度不同。 知道如何像这样对齐吗? 下面是手工制作的,仅用于可视化目的:

/paperarticles/Nov02-Bushswar.htm     time(s) accessed:   1 
/Documents/NinaSimone.htm             time(s) accessed:   1 
/cwi.css->                            time(s) accessed:   1

这是我对论坛的第一个问题。 我希望我做的一切都是正确的。 非常感谢你的帮助。 克里斯

制表符 (\t) 仅移动到 x 字符的下一个倍数(通常为 8 个),因此您的键的长度将落在不同的制表位上,您需要一些方法来确定在 output 字符串中放置多少个 \t。

更好的选择是确定最长键的宽度并将键串填充到 output 中的最大值。

maxKeyLen = max(map(len,accessedFiles.keys()))
for key,files in accessedFiles.items():
    output += key.ljust(maxKeyLen)+f" -> time(s) accessed is: {files}\n"

尝试使用格式方法:

"Location: {0:20} Revision {1}".format(Location,Revision)

您必须根据 label 的长度计算出每行的格式长度。 User 行需要比 Location 或 District 行更宽的格式宽度。

或者

您可以使用 expandtabs 来指定制表位,如下所示:

print ('Location:'+'10-10-10-10'+'\t'+ 'Revision: 1'.expandtabs(30))
print ('District: Tower'+'\t'+ 'Date: May 16, 2012'.expandtabs(30))

#Output:
Location:10-10-10-10          Revision: 1
District: Tower               Date: May 16, 2012

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM