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

306 Views Asked by At

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.

2

There are 2 best solutions below

1
On

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..
4
On

Minimal character count could even involve relying on your python implementation to release the file at the end of execution, rather than doing it explicitly:

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

Or using the p'' string to make a path in xonsh (this does properly close the file):

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

splitlines() already removes the new line characters, but not other whitespace.