简体   繁体   中英

Numbering each output line in Python

python: read in a file and repeat every line twice number the output lines

Example: Given this file:

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

Here is the output:

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

here's the code I have so far, I haven't been able to figure out the loop needed to put the double numbering at each line:

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

Are you saying the numbering needs to increment while pasting each line twice? So it needs to be: 1 Invictus

2 Invictus

3

4

5 Out of the night that covers me

If so, your loop should look like this:

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

Multiplication operator ( * ) might be handy.

Example:

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

Following the same logic:

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

You can use enumerate to keep count of your line number:

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

Or using the newer print function (required for 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='')

To get your exact output it looks like you skip the first line:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM