用行号python打印出每一行(从文件中) [英] Printing out each line (from file) with line number python

查看:734
本文介绍了用行号python打印出每一行(从文件中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个.txt文档,其中每个单词都在不同的行上

I have a .txt document with some words that are each on a different line

例如:

hello
too
me

我试图弄清楚如何打印每行以及每个单词所在的行号,但是从1开始,而不是0

I am trying to figure out how to print each line with the row number that each word is on but starting at 1, not 0

所需的输出:

1 = hello
2 = too
3 = me

我已经有一种解决方案,可以将文本文档中的行删除掉

I already have a solution for getting the lines out of the text document

open_file = open('something.txt', 'r')
lines = open_file.readlines()
for line in lines:
    line.strip()
    print(line)
open_file.close()

我知道我可以打印出每个单词所在的索引,除非我弄错了,否则它将从0而不是1开始.

I am aware that I could print out the index that each word is at however, unless I am mistaken, that would start the row number from 0 not 1. Thanks in advanced

推荐答案

您应该使用枚举器和迭代器,而不是将整个文件读取到内存中.

You should use enumerators and iterators rather than reading the entire file to memory:

with open('something.txt', 'r') as f:
    for i, line in enumerate(f, start=1):
        print('{} = {}'.format(i, line.strip()))

这篇关于用行号python打印出每一行(从文件中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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