Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way in xonsh to loop over the lines of a file?

Tags:

python

bash

xonsh

What is the best way in the xonsh shell to loop over the lines of a text file?

(A) At the moment I'm using

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

(B) Of course, there is also

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

I use (A) because it is shorter, but is there anything even more concise? And preferably folding the l.strip() into the loop?

Note: My main interest is conciseness (in the sense of a small character count) - maybe using xonsh's special syntax features if that helps the cause.

like image 352
halloleo Avatar asked Sep 04 '25 02:09

halloleo


1 Answers

You can fold str.strip() into the loop with 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..
like image 94
RoadRunner Avatar answered Sep 06 '25 19:09

RoadRunner