如何 !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 函数可能更好,但您可以使用 %magics 做很多相同的事情 - 如果您足够了解 shell。


要在 Python 表达式中使用 'magics',我必须使用底层函数,而不是 '!'或 '%' 语法,例如

import IPython
for txt in ['a.t1','b.t1','c.t1']:
    IPython.utils.process.getoutput('touch %s'%txt)

getoutput 函数由 %sx!! 的基础)使用,后者使用 subprocess.Popen。但是如果你去做所有这些工作,你还不如使用 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