小编Jar*_*ell的帖子

Python文件中的索引行

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

假设其内容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)

python indexing file

1
推荐指数
1
解决办法
2424
查看次数

标签 统计

file ×1

indexing ×1

python ×1