繁体   English   中英

如何!rm python_var(在Jupyter笔记本中)

[英]How to !rm python_var (in Jupyter notebooks)

我知道我可以这样做:

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

您可以在Python中处理此操作,而无需使用魔法Shell命令。 我建议使用pathlib模块,以获得更现代的方法。 对于您正在做的事情,它将是:

import pathlib
csv_files = pathlib.Path('/path/to/actual/files')
for csv_file in csv_files.glob('*.csv'):
    csv_file.unlink()

使用.glob()方法仅过滤要使用的文件,并使用.unlink()删除它们(类似于os.remove() )。

避免将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 (其underlies !! ),其使用subprocess.Popen 但是,如果您要进行所有工作,则最好使用Python本身提供的os函数。


文件名可能需要添加引号,以确保外壳程序不给出语法错误:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM