1.拷贝文件夹
remove_tree(self.dest_path) # 先删除已存在的目标文件夹,否则无法复制
shutil.copytree(self.src_path, self.dest_path, dirs_exist_ok=True)
2.移除整个文件夹和文件夹下所有内容
def remove_tree():
shutil.rmtree(self.src_root_path, onerror=self.rmtree_onerror)
def rmtree_onerror(self, func, path, exe_info):
if os.path.isfile(path):
os.chmod(path, stat.S_IWRITE)
os.remove(path)
elif os.path.isdir(path):
os.chmod(path, stat.S_IWRITE)
shutil.rmtree(path)
3.删除文件
if os.path.exists(src_path):
os.chmod(src_path, stat.S_IWRITE) # 去除只读属性,不然无法删除
os.remove(src_path)
4.递归遍历所有文件夹
命令
python Scan_Dir.py E:\badianboke
i控制层级
import os
import sys
class Scan_Dir():
def __init__(self, path):
self.path = path
def doScan(self):
self.scanItem(self.path, 0)
def scanItem(self, full_path, i):
if i > 3:
return
if os.path.isdir(full_path):
a = ''
for t in range(i):
a = a + ' '
print(a + os.path.basename(full_path))
list = os.listdir(full_path)
i = i + 1
for item in list:
temp = os.path.join(full_path, item)
if os.path.isdir(temp):
self.scanItem(temp, i)
if __name__ == '__main__':
task = Scan_Dir(sys.argv[1])
task.doScan()