在Python中为每个输出行编号

2024-10-03 06:18:36 发布

您现在位置: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

Tags: ofthefromthatascountoutme
3条回答

你是说每行粘贴两次时,编号需要增加吗?所以需要: 1不可侵犯

2不可侵犯

4个

5个晚上都在掩护我

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

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

乘法运算符(*)可能很方便。你知道吗

示例:

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

输入文件:

hello
world
my
name
is
Sait

输出.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

您可以使用enumerate对行号进行计数:

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

或者使用更新的print函数(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='')

相关问题 更多 >