使用 xonsh 通过 ls 遍历文件

Use xonsh to loop over files with ls

我想使用 xonsh 将多个文件压缩到一个目录中。我首先尝试使用以下方法:

$ ls
table_aa.csv    table_amgn.csv  table_csco.csv  table_esrx.csv  table_hal.csv  table_jbl.csv  table_pcg.csv   table_zmh.csv
table_aapl.csv  table_amzn.csv  table_d.csv     table_gas.csv   table_hp.csv   table_jpm.csv  table_usb.csv
$ for fn in ls:
..    bzip2 fn
..
NameError: name 'ls' is not defined

好的,所以我明确地使用 $()

$ for fn in $(ls).split():
.     bzip2 fn
bzip2: Can't open input file fn: No such file or directory.
bzip2: Can't open input file fn: No such file or directory.

有更好的方法吗?

$ xonsh --version
('xonsh/0.3.4',)

你与第二个例子非常接近。唯一需要注意的是 fn 是一个 Python 变量名,所以你必须使用 @() 将它传递给子进程:

$ for fn in $(ls).split(): . bzip2 @(fn)

此外,在 v0.3.4 上,您可以使用正则表达式替换 ls,

$ for fn in `.*`: . bzip2 @(fn)

至少在 master 上,您现在可以逐行遍历 !(),这意味着如果您习惯于 ls,以下内容也将起作用:

$ for fn in !(ls): . bzip2 @(fn)

使用ls

for fn in !(ls):
    print(fn.rstrip())

使用 glob(在正则表达式、shell 和路径变体中可用):

for fn in g`*`:
    print(fn)

使用 Python API(参见 os、glob 或 pathlib 模块):

import os
for fn in os.listdir():
    print(fn)