Home > database >  How do I display two number text files correctly?
How do I display two number text files correctly?

Time:12-13

I would to ask for solution regarding the file handling matter. The problem is when I try to print out the tuples from text file . Some digits or texts will be missing

Here's my code

        with open("ingredient.txt", 'r', encoding="utf8") as f1:
            myarray = f1.readlines()

        with open("quantity.txt", 'r', encoding="utf8") as f2:
            myarray2 = f2.readlines()  

        with open("demand.txt", 'r', encoding="utf8") as f3:
            myarray3 = f3.readlines()


        for element1,element7,element0 in zip(myarray, myarray2, myarray3):
            element1 = element1[:-1]
            element7 = element7[:-1]
            element0 = element0[:-1]
            print(f'{element1:<35}{element7:<11}{element0:>7}')

File : demand.txt = 30,20,50 quantity.txt = 10,10,1 ingredient.txt= tomato,tomato,tomato

What I got in my terminal is tomato 10 30 tomato 10 20 tomat 5 in parallel position

The outcome should be tomato 10 30 tomato 10 20 tomato 1 50 in parallel position

Thanks in advance !

CodePudding user response:

While there's some ambiguity to your formatting, my guess is that the lines

element1 = element1[:-1]
element7 = element7[:-1]
element0 = element0[:-1]

are meant to strip the newlines off the end. But the last element doesn't have a new line, so you get tomot instead of tomoto and you get nothing instead of 1. I would suggest using strip.

element1 = element1.strip()
element7 = element7.strip()
element0 = element0.strip()

and see if that works better.

CodePudding user response:

You can do it in a more compact way:

for e1, e2, e3 in zip(myarray, myarray2, myarray3):
    print(f'{e1.strip():<35}{e2.strip():<11}{e3.strip():>7}')
  • Related