在Python文件中建立索引行 [英] Indexing lines in a Python file

查看:433
本文介绍了在Python文件中建立索引行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打开一个文件,然后简单地返回该文件的内容,每行以行号开头.

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

假设a的内容是

a

b

c

我希望结果是

1: a

2: b

3: c

我有点困惑,尝试枚举,但没有给我想要的格式.

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

是针对Uni的,但仅是一项实践测试.

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

推荐答案

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

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

这篇关于在Python文件中建立索引行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆