rm 每次调用可以删除多个文件:
In [80]: !touch a.t1 b.t1 c.t1
In [81]: !ls *.t1
a.t1 b.t1 c.t1
In [82]: !rm -r a.t1 b.t1 c.t1
In [83]: !ls *.t1
ls: cannot access '*.t1': No such file or directory
如果起点是文件名列表:
In [116]: alist = ['a.t1', 'b.t1', 'c.t1']
In [117]: astr = ' '.join(alist) # make a string
In [118]: !echo $astr # variable substitution as in BASH
a.t1 b.t1 c.t1
In [119]: !touch $astr # make 3 files
In [120]: ls *.t1
a.t1 b.t1 c.t1
In [121]: !rm -r $astr # remove them
In [122]: ls *.t1
ls: cannot access '*.t1': No such file or directory
使用 Python 自己的操作系统函数可能会更好,但是如果你对 shell 有足够的了解,你可以使用 %magics 做很多相同的事情。
要在 Python 表达式中使用“魔法”,我必须使用底层函数,而不是“!”或 '%' 语法,例如
import IPython
for txt in ['a.t1','b.t1','c.t1']:
IPython.utils.process.getoutput('touch %s'%txt)
getoutput 函数由使用subprocess.Popen 的%sx(!! 的基础)使用。但是,如果您从事所有这些工作,您不妨使用 Python 本身提供的 os 函数。
文件名可能需要添加一层引用以确保 shell 不会给出语法错误:
In [129]: alist = ['"a(1).t1"', '"b(2).t1"', 'c.t1']
In [130]: astr = ' '.join(alist)
In [131]: !touch $astr
In [132]: !ls *.t1
'a(1).t1' a.t1 'b(2).t1' b.t1 c.t1