[英]How to print output of multiple txt file in tabular format with Python code?
[英]Python 3.9 - How to print and format a .txt file?
我将如何定义一个函数,以便在不更改文件内容的情况下以特定方式打印文本文件? 或者也许有什么更有效的方法来解决这个问题?
文本文件:
menu.txt
Cheese Burger, 5.00
Chicken Burger, 4.50
Fries, 2.00
Onion Rings, 2.50
Drinks, 1.50
期望的输出:
1. Cheese Burger 5.00
2. Chicken Burger 4.50
3. Fries 2.00
4. Onion Rings 2.50
5. Drinks 1.50
您可以使用enumerate
获取从1
开始的序列号。
要按照您提到的方式打印输出,您需要使用String formatting
- Docs
我使用了{item:25}
- 这将使项目的宽度为 25。您可以输入任何您希望获得所需空间的数字。
从文档:
在 ':' 之后传递一个整数将导致该字段的字符数最少。 这对于使列对齐很有用。
with open('menu.txt', 'r') as f:
lines = f.readlines()
for i,v in enumerate(lines,1):
item, price = v.strip('\n').split(',')
print(f'{i}. {item:25}{price}')
Output
1. Cheese Burger 5.00
2. Chicken Burger 4.50
3. Fries 2.00
4. Onion Rings 2.50
5. Drinks 1.50
您应该以读取(“r”)模式打开文件以使用它而不进行更改。 ./Menu.txt 表示文件和 .py 文件在同一个文件夹中。 你可以写确切的路径而不是“./Menu.txt”。
file = open("./Menu.txt", "r")
lines = file.readlines()
file.close()
num_of_line = 1
for line in lines:
res = line.split(", ")
print(num_of_line, end=". ")
print(f"{res[0] : <20}{res[1] : ^5}")
num_of_line += 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.