我有一个正在解析的json文件,它给了我一些路径,比如-abc1/xyz2/file1.txt我必须将此文件复制到另一个位置(例如-/scratch/userdid/pp(
我知道有一个类似的bashcp-n file.txt--parents/strack/userid/pp
我可以在python中的os.system((中使用它,它可以一次创建目录结构并复制文件。
这是总结脚本
#!/usr/bin/python
def parse_json():
//parse json file
def some():
#get a list and create dirs = list length
for i in len(list):
dir = TASK + str(i)
os.makedir(dir)
path=abc1/xyz2/file1.txt
os.system('cp -n path --parents /scratch/userid/pp')
这必须对多个文件和多次进行
我知道这很有效,但我正在寻找一种更像蟒蛇的方式(一句话可能是b(来做到这一点我试过
os.chdir(/scratch/userid/pp)
#split path to get folder and file
os.makedirs(path)
os.chdir(path)
shutil.copy(src, dest)
但是,与bash 中的一行相比,每个文件都涉及大量makedir和chdir
您可以直接从python使用shutil,而无需操作系统包
示例:
from shutil import copyfile
source_file="/home/user/file.txt"
destinaton_file="/home/user/folder/file.txt"
copyfile(source_file, destinaton_file)
您也可以使用子进程(python 3+(或命令(python 2+(在python 中执行复制shell命令