Indexing lines in a Python file

2019-07-30 12:58发布

I want to open a file, and simply return the contents of said file with each line beginning with the line number.

So hypothetically if the contents of a is

a

b

c

I would like the result to be

1: a

2: b

3: c

Im kind of stuck, tried enumerating but it doesn't give me the desired format.

Is for Uni, but only a practice test.

A couple bits of trial code to prove I have no idea what I'm doing / where to start

def print_numbered_lines(filename):
    """returns the infile data with a line number infront of the contents"""
    in_file = open(filename, 'r').readlines()
    list_1 = []
    for line in in_file:
        for item in line:
            item.index(item)
            list_1.append(item)
    return list_1

def print_numbered_lines(filename):
    """returns the infile data with a line number infront of the contents"""
    in_file = open(filename, 'r').readlines()
    result = []
    for i in in_file:
        result.append(enumerate(i))
    return result

3条回答
成全新的幸福
2楼-- · 2019-07-30 13:44

What about using an OrderedDict

from collections import OrderedDict

c = OrderedDict()
n = 1
with open('file.txt', 'r') as f:
    for line in f:
        c.update({n:line})
        #if you just want to print it, skip the dict part and just do:
        print n,line
        n += 1

Then you can print it out with:

for n,line in c.iteritems(): #.items() if Python3
    print k,line
查看更多
家丑人穷心不美
3楼-- · 2019-07-30 13:46

There seems no need to write a python script, awk would solve your problem.

 awk '{print NR": "$1}' your_file > new_file
查看更多
SAY GOODBYE
4楼-- · 2019-07-30 13:51

A file handle can be treated as an iterable.

with open('tree_game2.txt') as f:
   for i, line in enumerate(f):
   print ("{0}: {1}".format(i+1,line))
查看更多
登录 后发表回答