首选的文件一行一行在Python中读取习惯用法 [英] Preferred file line by line read idiom in Python

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

问题描述

我感觉几乎每次我用Python读文件时,我想要的是:

pre $ with open(filename )file_handle:
for file_handle中的行:
#do something

这真的是最好的成语吗?它温和地激怒我,这双重缩进所有文件阅读逻辑。有没有办法将这个逻辑折叠成一行或一个图层?

解决方案

对于简单的情况,是的,两级对于是惯用的。 缩进成为一个问题,在Python的其他地方,这个惯用的解决方案是找到一些东西来分解成一个函数。






你可以编写包装来帮助你。例如,下面是一个简单的方法来解决你用来解决的一些问题(例如,即使在最好的情况下,文件在完成循环之后仍然存在,直到如果范围是主事件循环或生成器或其他东西...):

  def with_iter(可迭代的):
与可迭代:
从可迭代的收益

在with_iter中的行(open(filename)):
(打开(other_filename)):
$做别的事情
$ / code>

当然,这并不能解决所有问题。 (请参阅此ActiveState配方)。



如果你知道它是做你想做的,那很好。如果你不了解差异......坚持什么是惯用的;这是一个惯用的原因。






那么,你如何重构代码呢?最简单的方法往往是把循环体转换成一个函数,所以你可以使用 map 或理解:



< pre $ def do_with_line(行):
返回行
$ b $打开(filename)作为f:
process = [do_with_line行)在f中的行

但是如果问题出在上面或下面的代码 for 太深了,你必须在不同的层次重构。


I feel like almost every time I read a file in Python, what I want is:

with open("filename") as file_handle:
    for line in file_handle:
        #do something

Is this truly the preferred idiom? It mildly irritates me that this double indents all file reading logic. Is there a way to collapse this logic into one line or one layer?

解决方案

For simple cases, yes, the two-level with and for is idiomatic.

For cases where the indentation becomes a problem, here as anywhere else in Python, the idiomatic solution is to find something to factor out into a function.


You can write wrappers to help this. For example, here's a simple way to solve some of the problems you use with for (e.g., even in the best case, the file sticks around after you finish the loop, until the end of the scope—which could be days later, or never, if the scope is a main event loop or a generator or something…):

def with_iter(iterable):
    with iterable:
        yield from iterable

for line in with_iter(open("filename")):
    # do something

for line in with_iter(open("other_filename")):
    # do something else

Of course it doesn't solve everything. (See this ActiveState recipe for more details.)

If you know that it does what you want, great. If you don't understand the differences… stick to what's idiomatic; it's idiomatic for a reason.


So, how do you refactor the code? The simplest way is often to turn the loop body into a function, so you can just use map or a comprehension:

def do_with_line(line):
    return line

with open("filename") as f:
    process = [do_with_line(line) for line in f]

But if the problem is that the code above or underneath the for is too deep, you'll have to refactor at a different level.

这篇关于首选的文件一行一行在Python中读取习惯用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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