Python文件中的索引行

Jar*_*ell 1 python indexing file

我想打开一个文件,只需返回所述文件的内容,每行以行号开头.

假设其内容a是假设的

a

b

c
Run Code Online (Sandbox Code Playgroud)

我希望结果如此

1: a

2: b

3: c
Run Code Online (Sandbox Code Playgroud)

我有点卡住,尝试枚举,但它没有给我所需的格式.

适用于Uni,但仅限于练习测试.

一些试验代码证明我不知道我在做什么/从哪里开始

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
Run Code Online (Sandbox Code Playgroud)

e4c*_*4c5 6

文件句柄可以视为可迭代.

with open('tree_game2.txt') as f:
   for i, line in enumerate(f):
   print ("{0}: {1}".format(i+1,line))
Run Code Online (Sandbox Code Playgroud)

  • 你可以传递枚举起始值:`enumerate(f,1)`.那时不需要"+ 1". (4认同)