python - 进入子目录、运行命令然后返回的最优雅的方式是什么?

标签 python operating-system glob tar

我有以下目录结构。

 data
│   ├── 2019-12-11
│   └── 2019-12-12
│       ├── ADAZ19.json
│       ├── BCHZ19.json

我想进入,从 os.system 运行 tar 命令,然后返回到我开始的地方。

我尝试了如下所示:

# Full filepath from root.
import os
path_to_file = 'data/2019-12-12/' # This is generated dynamically.
file = 'ADAZ19.json' # This is generated dynamically.
cur_dir = os.getcwd()
os.system(f'tar -czf {cur_dir}{path_to_file}{file}.tar.gz {cur_dir}{path_to_file}{file}')

这不起作用。所以现在我想进入 path_to_file,直接在文件上运行 tar,然后返回到我开始的位置。请注意,path_to_file 由用户设置,不能进行硬编码。

我想进入子目录,以便目录结构不会与文件一起被压缩。最优雅的方法是什么?

最佳答案

使用“CHange DIRECory”更改文件夹

 os.chdir(folder)

import os

path_to_file = 'data/2019-12-12/'
file = 'ADAZ19.json'

cur_dir = os.getcwd()

os.chdir(path_to_file) # change folder

os.system(f'tar -czf {file}.tar.gz {file}')

os.chdir(cur_dir) # go back

编辑:但是你可以使用 python 标准模块 tarfile创建它。

然后您不必更改文件夹,但必须在

中使用第二个参数
add(added_file, name_in_tar_file)

设置不带路径的名称。

import tarfile

path_to_file = 'data/2019-12-12/'
file = 'ADAZ19.json'

t = tarfile.open(f'{path_to_file}{file}.tar.gz', mode='w:gz')

t.add(f'{path_to_file}{file}', file) # second argument without path to file

t.close()

关于python - 进入子目录、运行命令然后返回的最优雅的方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59331908/

相关文章:

php glob模式匹配任意数字

Python Fileinput openhook=fileinput.hook_compressed 语法使用

python - `pip install pyside` 在 Linux 上卡住?

python - 如何从 numpy 数组中提取任意行值?

java - 临时文件夹被创建为临时文件

python - 在 python 中获取 os.system 的输出并在之后处理它

python - 在列表中搜索

python - python 列表的 Yaml 转储使用内联格式而不是连字符 + 空格

ruby - Ruby 语言可以用来构建操作系统吗?

Java 6 上的 java.nio.Files、java.nio.Paths