我知道我可以这样做:
CSV_Files = [file1.csv, file2.csv, etc...]
%rm file1.csv
!rm file2.csv
但是我该如何做为变量。例如。
TXT_Files = [ABC.txt, XYZ.txt, etc...]
for file in TXT_Files:
!rm file
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自己的OS功能可能会更好,但是如果您对Shell的了解足够,则可以使用%magics进行很多相同的事情。
要在Python表达式中使用“魔术”,我必须使用底层函数,而不是“!”。或'%'语法,例如
import IPython
for txt in ['a.t1','b.t1','c.t1']:
IPython.utils.process.getoutput('touch %s'%txt)
该getoutput
函数由%sx
(!!
使用)(使用)使用subprocess.Popen
。但是,如果您进行所有工作,那么您可能还需要使用os
Python本身提供的功能。
文件名可能需要添加引号,以确保外壳程序不会出现语法错误:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句