-1

Say I have a couple of text files, fruit.txt and veg.txt which look like,

Apple
Pear
Orange

Brocolli
Cucumber
Spinach

I have a couple of for loops that print out the contents of the .txt files,

       for line in fruit:
            fields = line.split("\n")   
            col = fields[0]
            print(col)
        for line in veg:
            fields = line.split("\n")   
            col1 = fields[0]
            print(col1)

And the output I get is,

Apple
Pear
Orange
Brocolli
Cucumber
Spinach

I want to try and print it side by side like,

Apple Brocolli
Pear Cucumber
Orange Spinach 
Ken Doe
  • 121
  • 7

2 Answers2

3

You can use the format method in builtin strings, and zip_longest.

from itertools import zip_longest
...
# Assuming fruit is file_context.readlines()
fruits = fruit.split("\n")
vegs = veg.split("\n")
for l1,l2 in zip_longest(fruits, vegs, fillvalue=""):
    print("{}\t{}".format(l1, l2))   

zip_longest will take care of the situation where you have unequal number of fruits and vegs.

NOTE: The above will work in python 3. For python 2, remember to replace:

from itertools import zip_longest

with:

from itertools import izip_longest
OneRaynyDay
  • 3,658
  • 2
  • 23
  • 56
1

An easier way would be to use the readlines method like so, and the 'end' parameter is the printed value that prints at the end, by default its value is '\n'

fruits = fruit.readlines()   
vegs = veg.readlines() 

for i in range(min(len(vegs),len(fruits))):
    print(fruits[i],end="\t")
    print(vegs[i])
marc
  • 914
  • 6
  • 18
  • For this method, I am assuming it doesn't work for uneven lists? Because I get an IndexError when I try. – Ken Doe Apr 21 '18 at 22:21
  • This should work for uneven lists because "i" is actually taking the "min" value of "len(fruits)" and "len(vegs)", make sure you copied the min part. – marc Apr 23 '18 at 09:04