4

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.

halloleo
  • 9,216
  • 13
  • 64
  • 122

2 Answers2

2

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..
halloleo
  • 9,216
  • 13
  • 64
  • 122
RoadRunner
  • 25,803
  • 6
  • 42
  • 75
1

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.

halloleo
  • 9,216
  • 13
  • 64
  • 122
soundstripe
  • 1,454
  • 11
  • 19