[英]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.. 我已经尝试过readline,但是我很困惑。
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: 在这里,我有data.txt
,其中包含如下数据:
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
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 : 您可以创建一个列表来存储每3次迭代的行,然后将其附加到last_q
,最后您可以使用zip
函数对last_q
进行压缩,并使用\\t
将其配对,然后再次写入文件:
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
I'm a particular fan of the itertools
grouper
recipe for things like this. 对于这样的事情,我特别喜欢itertools
grouper
食谱。
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)
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]
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.