【问题标题】:How to !rm python_var (in Jupyter notebooks)如何 !rm python_var(在 Jupyter 笔记本中)
【发布时间】:2018-12-28 23:35:54
【问题描述】:

我知道我能做到:

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

【问题讨论】:

  • 为什么需要使用shell? CSV_Files.map(os.remove)
  • 只是新手不想导入操作系统的烦恼。想知道我是否可以循环执行此操作。 [os.remove(file) for file in Files] 效果很好。

标签: python bash jupyter rm


【解决方案1】:

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

【讨论】:

  • 这很好,但不能循环工作。 '/bin/sh: 1: 语法错误:“(”意外'
  • 神奇的语法'!'和 '%' (和不带引号的字符串)不是有效的 Python,因此在循环等 Python 结构中不起作用。这些表达式必须在 IPython REPL 可以捕获和解析它们的顶层使用。
  • 等等,这是因为我在 str 中有括号(在列表中)。例如。 files = ['Hello(1).csv', 'Hello(2).csv']
  • 否则它可以完美运行。谢谢!这就是我想要的
  • 您可能需要添加一层引号,例如'"Hello(1).csv"'.
【解决方案2】:

您可以在 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 作为变量,因为它是语言中的保留字。

【讨论】:

    猜你喜欢
    • 2020-05-17
    • 1970-01-01
    • 1970-01-01
    • 2021-09-18
    • 2019-01-02
    • 2023-03-19
    • 1970-01-01
    • 2019-05-10
    • 1970-01-01
    相关资源
    最近更新 更多