繁体   English   中英

如何在txt文件上使用枚举函数?

[英]How to use the enumerate function on a txt file?

我正在尝试读取我之前在控制台上创建的 Hi.txt 文件,但不是仅仅从中获取值,而是尝试使用 enumerate 函数在它旁边添加索引值。 (假设文本文件中有 3 个元素)。

with open('Hi.txt','r') as hello:
    x = hello.read()
    print(x)

根据我的理解,这段代码将遍历该 txt 文件中的元素,如下所示:

Dave
Jack
Mary

但是,当我尝试这样的事情时:

with open('Hi.txt','r') as hello:
    x = hello.read()
    for i,v in enumerate(x,1):
        print(i,v)

它一个一个地打印出每个字符。

期望的输出:

1 Dave
2 Jack
3 Mary

您枚举文件句柄本身:

with open('/Hi.txt','r') as hello:
    for i,v in enumerate(hello,1):
        print(i,v, end="")

你可以这样做:

with open('Hi.txt','r') as hello:
    for i,v in enumerate(hello.readlines(), 1):
        print(i,v, end="")

这将迭代文件中的所有行(假设您将所有文件项都放在分隔行中)。

暂无
暂无

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

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