繁体   English   中英

Python 文件中的索引行

[英]Indexing lines in a Python file

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

因此,如果假设的内容, a

a

b

c

我希望结果是

1: a

2: b

3: c

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

是给 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

文件句柄可以被视为可迭代对象。

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

似乎没有必要写一个 python 脚本, awk可以解决你的问题。

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

使用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

然后你可以打印出来:

for n,line in c.iteritems(): #.items() if Python3
    print k,line

这样做的简单方法: 1st:打开文件 -----2ed:使用计数机制:例如:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM