Search code examples
pythonreadlines

how to adding new tab in readline python


I have a problem can't adding a new tab in reading file.
I've tried readline, but I am confused..

f = open('data.txt', 'r')
count = 0
for i in f.readlines():
     count += 1
     if count == 3:
          #adding new tab
     print i,

In here, I have data.txt which contains data like this:

af  Afrikaans
sq  Albanian
ar  Arabic
hy  Armenian
az  Azerbaijani
eu  Basque

But I can't adding new tab if the data is in a certain count readline.
I want to make it like this..

af  Afrikaans      hy   Armenian
sq  Albanian       az   Azerbaijani
ar  Arabic         eu   Basque

Solution

  • below is the code that will do what you aim to accomplish, hope it is what you want:

    f = open('data.txt','r')
    lines = [l.strip() for l in f.readlines()]
    l = len(lines)
    for i in range(l/2):
        print lines[i]+'\t'+ lines[i + l/2]
    if l%2: #if it is odd
        print lines[-1]