我有以下目录结构。
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/