Jared Rendell
Jared Rendell

Reputation: 41

Indexing lines in a Python file

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

Upvotes: 1

Views: 17091

Answers (4)

funhaha
funhaha

Reputation: 1

the simple way to do it: 1st:with open the file -----2ed:using count mechanism: for example:

data = object of file.read()
lines = data.split("\n")

count =0
for line in lines:
    print("line "+str(count)+">"+str()+line)
    count+=1

Upvotes: 0

e4c5
e4c5

Reputation: 53744

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

Upvotes: 8

alec_djinn
alec_djinn

Reputation: 10799

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

Upvotes: 0

luoluo
luoluo

Reputation: 5533

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

 awk '{print NR": "$1}' your_file > new_file

Upvotes: 1

Related Questions