简体   繁体   中英

Python 3.9 - How to print and format a .txt file?

How would I define a function so that the text file may printed out in a particular way without changing the contents of the file? Or perhaps what would be a more efficient method of going about this?

Text file:

menu.txt
Cheese Burger, 5.00
Chicken Burger, 4.50
Fries, 2.00
Onion Rings, 2.50
Drinks, 1.50

Desired output:

1.  Cheese Burger           5.00
2.  Chicken Burger          4.50        
3.  Fries                   2.00
4.  Onion Rings             2.50
5.  Drinks                  1.50

You can use enumerate to get that serial numbers starting from 1 .

To print the output the way you mentioned you need to use String formatting - Docs

I have used {item:25} - This will make the item to be of width 25. You can put whatever number you wish to get desired space.

From the Docs:

Passing an integer after the ':' will cause that field to be a minimum number of characters wide. This is useful for making columns line up.

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

You should open file in read ("r") mode to use it without changing. ./Menu.txt means the file and .py file are in the same folder. You can write exact path instead of "./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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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