如何在 readline python 中添加新标签

how to adding new tab in readline python

我无法在阅读文件中添加新选项卡。
我试过 readline,但我很困惑..

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

在这里,我有 data.txt,其中包含这样的数据:

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

但是如果数据在特定的计数读取行中,我无法添加新标签。
我想做成这样..

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

您可以创建一个列表来存储每 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')

演示:

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')]

最终结果:

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

我想你想要的实际上是在同一行上打印两行不同的行,用制表符分隔。所以你必须阅读所有内容,然后打印它们并在中间插入标签。像这样:

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]

下面是将完成您的目标的代码,希望它是您想要的:

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]

我特别喜欢 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))

这可以很好地模块化

# 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)