Reputation: 97
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
Upvotes: 0
Views: 398
Reputation: 107307
you can create one list to store your lines per 3 iteration then append this it to last_q
and at last you can use zip
function to zip last_q
and join the pairs with \t
then write to file again :
import copy
q = []
last_q= []
with open('newefile.txt','r') as f:
for line in f:
q.append(line.strip())
if len(q)==3 :
last_q.append(copy.copy(q))
q=[]
with open('newefile.txt','w') as f:
for lines in zip(*last_q) :
print lines
f.write('\t'.join(lines)+'\n')
Demo :
print last_q
deque([deque(['af Afrikaans\thy Armenian', 'sq Albanian\taz Azerbaijani', 'ar Arabic\teu Basque'], maxlen=3)])
print zip(*last_q)
[('af Afrikaans', 'hy Armenian'), ('sq Albanian', 'az Azerbaijani'), ('ar Arabic', 'eu Basque')]
Final result :
af Afrikaans hy Armenian
sq Albanian az Azerbaijani
ar Arabic eu Basque
Upvotes: 1
Reputation: 54213
I'm a particular fan of the itertools
grouper
recipe for things like this.
from itertools import zip_longest
# in Python2 do:
## from itertools import izip_longest
data = """af Afrikaans
sq Albanian
ar Arabic
hy Armenian
az Azerbaijani
eu Basque""".splitlines()
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return zip_longest(*args, fillvalue=fillvalue)
for line in zip(*grouper(data, 3, '')):
print('\t'.join(line))
This can be nicely modular
# tablefy.py
from itertools import zip_longest
def rows(data, max_rows=None, columndelimiter="\t"):
"""Produces rows, squeezing extra data into max_rows by
adding columns delimited by columndelimiter"""
# rows(['a','b','c','d'], 3, " ") --> ['a d', 'b ', 'c ']
if max_rows is None:
return (row for row in data)
def _grouper(iterable, n, fillvalue=None):
"""Collect data into fixed-length chunks or blocks"""
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
args = [iter(iterable)] * n
return zip_longest(*args, fillvalue=fillvalue)
for line in _grouper(data, max_rows, fillvalue=""):
yield "\t".join(line)
# my_file.py
data = """af Afrikaans
sq Albanian
ar Arabic
hy Armenian
az Azerbaijani
eu Basque""".splitlines()
import tablefy
for row in tablefy.rows(data, max_rows=3):
print(row)
Upvotes: 1
Reputation: 859
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]
Upvotes: -1
Reputation: 1
I think what you want is actually print two different lines on the same line, separated by a tab. So you would have to read them all and then print them with the tab in the middle. Something like this:
f = open('data.txt', 'r')
lines = []
for i in f.readlines():
lines.append(i.replace("\n", ""))
for i in range(0, len(lines)/2):
print lines[i] + "\t" + lines[len(lines)/2 + i]
Upvotes: 0