代码之家  ›  专栏  ›  技术社区  ›  halloleo

在xonsh中,循环文件行的最佳方式是什么?

  •  2
  • halloleo  · 技术社区  · 7 年前

    什么是最好的方法 xonsh 要在文本文件行上循环的shell?

    (a) 目前我正在使用

    for l in !(cat file.txt): 
        line = l.strip()
        # Do something with line...
    

    (b) 当然,还有

    with open(p'file.txt') as f:
        for l in f:
            line = l.strip()
            # Do something with line...
    

    我用(a)是因为它比较短,但是 还有更简洁的吗? 最好折叠 l.strip() 进入循环?

    注: 我的主要兴趣是简洁性(在一个小字符计数的意义上)——如果这有助于原因的话,也许可以使用xonsh的特殊语法特性。

    2 回复  |  直到 7 年前
        1
  •  2
  •   halloleo    7 年前

    你可以折叠 str.strip() 进入循环 map() :

    (a):

    for l in map(str.strip, !(cat file.txt)):
        # Do something with line...
    

    (b):

    with open('file.txt') as f:
        for l in map(str.strip, f):
            # Do something with l..
    
        2
  •  1
  •   halloleo    7 年前

    最小字符数甚至可能涉及依赖python实现在执行结束时释放文件,而不是显式地执行:

    for l in map(str.strip, open('file.txt')):
        # do stuff with l
    

    或者使用p“”字符串在xonsh中创建路径(这会正确关闭文件):

    for l in p'file.txt'.read_text().splitlines():
        # do stuff with l
    

    splitlines() 已删除新行字符,但不删除其他空白。

    推荐文章