在Python中为每个输出行编号

时间:2015-10-13 02:33:03

标签: python

python:读取文件并重复每一行两次         编号输出行

实施例: 鉴于此文件:

Invictus

Out of the night that covers me
Black as the pit from pole to pole
I thank whatever gods there may be
For my unconquerable soul

这是输出:

1 Invictus
1 Invictus
2
2
3 Out of the night that covers me
3 Out of the night that covers me
4 Black as the pit from pole to pole
4 Black as the pit from pole to pole
5 I thank whatever gods there may be
5 I thank whatever gods there may be
6 For my unconquerable soul
6 For my unconquerable soul

这是我到目前为止的代码,我还没有找到在每一行放置双重编号所需的循环:

fileicareabout = open("ourownfile","r")
text = fileicareabout.readlines()
count = len(open("ourownfile").readlines(  ))
fileicareabout.close()
def linecount(ourownfile):
    count = 0
    for x in open("ourownfile"):
        count += 1
    return count

for words in text:
    print (str(linecount) + words) * 2
print

3 个答案:

答案 0 :(得分:1)

您是否说在将每行粘贴两次时需要增加编号?所以它需要是: 1 Invictus

2 Invictus

3

4

5夜间覆盖我

如果是这样,你的循环应如下所示:

count = 0
for words in text:
      print(str(count) + words)
      count += 1
      print(str(count) + words)
      count += 1

答案 1 :(得分:0)

乘法运算符(*)可能很方便。

示例:

>>> '15 hello world\n' * 2
'15 hello world\n15 hello world\n'

遵循相同的逻辑:

counter = 1
with open('input.txt') as input_file:
    with open('output.txt', 'w') as output_file:
        for line in input_file:
            output_file.write( '{} {}'.format(counter, line) * 2  )
            counter += 1

<强> input.txt中:

hello
world
my
name
is
Sait

<强> output.txt的:

1 hello
1 hello
2 world
2 world
3 my
3 my
4 name
4 name
5 is
5 is
6 Sait
6 Sait

答案 2 :(得分:0)

您可以使用枚举来统计您的行号:

with open("ourownfile") as f:
    for line_no, line in enumerate(f, 1):
        print "{} {}".format(line_no, line)*2,

或使用较新的打印功能(python 3需要):

from __future__ import print_function

with open("ourownfile") as f:
    for line_no, line in enumerate(f, 1):
        print("{} {}".format(line_no, line)*2, end='')

要获得确切的输出,您似乎跳过了第一行:

with open("ourownfile") as f:
    for line_no, line in enumerate(f):
        if line_no == 0:
            continue
        print("{} {}".format(line_no, line)*2, end='')