需求:要从服务器上的某个目录中抽取(复制整个目录结构)需要的文件(目录),到其他的目录下
实现:以下是源目录结构
[root@ilovelluvia ~]# tree /teddylu
/teddylu
|-- a
| |-- html
| | |-- 1.html
| | |-- 2.html
| | |-- 3.html
| | |-- 4.html
| | `-- 5.html
| `-- images
| |-- 10.jpg
| |-- 1.jpg
| |-- 2.jpg
| |-- 3.jpg
| |-- 4.jpg
| |-- 5.jpg
| |-- 6.jpg
| |-- 7.jpg
| |-- 8.jpg
| `-- 9.jpg
|-- b
| |-- html
| | |-- a.html
| | |-- b.html
| | |-- c.html
| | `-- d.html
| `-- images
| |-- 1.jpg
| |-- 2.jpg
| |-- 3.jpg
| |-- 4.jpg
| |-- 5.jpg
| `-- 6.jpg
|-- c
| |-- html
| `-- images
| |-- 10.png
| |-- 1.png
| |-- 2.png
| |-- 3.png
| |-- 4.png
| |-- 5.png
| |-- 6.png
| |-- 7.png
| |-- 8.png
| `-- 9.png
`-- d
|-- html
`-- images
12 directories, 35 files
需要被抽取的文件列表:
[root@ilovelluvia ~]# cat list.txt /a/html/1.html /a/html/2.html /a/html/3.html /a/images /b/html/a.html /b/html/c.html /c/images/1.png /c/images/2.png /c/images/3.png /c/images/1997.png
脚本:
[root@ilovelluvia ~]# cat copy.py
import os
import shutil
source_root_dir='/teddylu'
target_root_dir='/lluvia'
if os.path.exists(target_root_dir):
print(target_root_dir + ' does exist')
shutil.rmtree(target_root_dir)
print('##########稍等##########')
print(target_root_dir + ' has deleted')
os.makedirs(target_root_dir)
print('##########稍等##########')
print(target_root_dir + ' has created')
filename='list.txt'
with open(filename) as fl:
for f in fl.readlines():
f=f.strip()
#print(f)
source_file_path=source_root_dir+f
target_file_path=target_root_dir+f
#print('##########start##########')
#print(source_file_path)
#print(target_file_path)
#print('##########end##########')
if os.path.isfile(source_file_path):
target_list=target_file_path.split('/')[:-1]
#print(target_list)
target_new_path='/'.join(target_list)
#print(target_new_path)
os.system('mkdir -p '+ target_new_path)
os.system('cp '+source_file_path+' '+target_new_path+'/')
print('File' + target_file_path +' has copied sucessfully.')
elif os.path.isdir(source_file_path):
_target_list=target_file_path.split('/')[:-1]
#print(_target_list)
_target_path='/'.join(_target_list)
#print(_target_path)
os.system('mkdir -p '+_target_path)
os.system('cp -r '+source_file_path+' '+_target_path)
print('Folders' + target_file_path +' has copied sucessfully.')
else:
#print(source_file_path)
#print(source_file_path+ " does not exist." )
print('error:')
print(source_file_path+" does not exist")
参考
1.https://blog.csdn.net/weixin_41004350/article/details/102998855
2.https://www.cnblogs.com/yyxayz/p/4034299.html
Python抽取文件

