简体   繁体   English

使用索引,打开(文件)作为枚举(文件指针)

[英]With index, open(file) as enumerate(filepointer)

I'm trying to open a file using the with syntax while also enumerating the file's lines. 我正在尝试使用with语法打开文件with同时还要枚举文件的行。

So I tried this: 所以我尝试了这个:

with index, open(filename) as enumerate(f):
    f.read()...

Where f is meant to correspond to open(filename) , and index should take enumerate(f) . 其中f表示对应于open(filename) ,而index应该采用enumerate(f) So I want to be able to call f.read() in the body, and know which line of the file is being processed. 因此,我希望能够在主体中调用f.read() ,并知道文件的哪一行正在处理。

I'm sure this can be done -- I'm just not using the syntax correctly. 我敢肯定这是可以做到的-我只是没有正确使用语法。 Any help? 有什么帮助吗?

I think the closest thing that's valid Python to what you're trying is this: 我认为最有效的Python与您尝试的最接近的是:

with open(filename) as f:
    for index, line in enumerate(f):
        # Do stuff with each line.

f.read() reads the entire contents of f and stores it in a string, so you wouldn't be able to get line numbers that way. f.read()读取f的全部内容并将其存储在字符串中,因此您将无法以这种方式获取行号。

You can't combine the enumerate call with the with statement because the language's grammar just doesn't allow it : 您不能将enumerate调用与with语句结合使用with因为该语言的语法不允许这样做

 with_stmt ::= "with" with_item ("," with_item)* ":" suite with_item ::= expression ["as" target] 

The execution of the with statement with one “item” proceeds as follows: 用一个“项目”执行with语句的过程如下:

  1. The context expression (the expression given in the with_item) is evaluated to obtain a context manager. 计算上下文表达式(with_item中给出的表达式)以获得上下文管理器。

  2. The context manager's __exit__() is loaded for later use. 上下文管理器的__exit__()已加载以供以后使用。

  3. The context manager's __enter__() method is invoked. 上下文管理器的__enter__()方法被调用。

  4. If a target was included in the with statement, the return value from __enter__() is assigned to it. 如果with语句中包含target ,则将__enter__()的返回值分配给它。

target is meant to be a variable that the return value of open(filename) is assigned to. target是要为open(filename)的返回值分配的变量。 It can't be a function call. 不能是函数调用。

You seem to be confusing the with statement with the for statement. 您似乎将with语句与for语句混淆了。 In

for i, x in enumerate(lst):

i and x are set to the values obtained from the iterator created by enumerate . ix设置为从enumerate创建的迭代器获得的值。 In

with open(filename) as f:

f is assigned the return value of open . f分配了open的返回值。

You cannot mix the two. 您不能将两者混在一起。 You need to use two separate statements: 您需要使用两个单独的语句:

with open(filename) as f:
    for index, line in enumerate(f):

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

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