Python (12) - delete folders and files

Folder deletion


Tips: If a string path
to import library files:
Import os, shutil

1. Delete a file folder, it can not be used to delete a folder.

os.remove(’./cyy_est/subtest1/file_cyy’)

2. Delete an empty folder, if the folder there are files or folders are deleted unsuccessful.

os.removedirs(’./cyy_test/subtest123’)

3. To delete a folder (if the folder there are files will be deleted together)

shutil.rmtree ( './ cyy_test / subtest2')

4. If you want to delete a file while retaining the folder structure, you can choose to traverse delete files

 
import os
g=os.walk('/home/abc/Desktop/cyy_test')
for path,dir,files in g:  #路径path 文件夹中的文件名files和文件夹名dir(都是list)
	print(path,dir,files)
	while files!=[]:
		for file in files:
			print(file)
			os.remove(os.path.join(path,file))
			files.remove(file)
print('end')

From the top down traversal to all folders
Here Insert Picture Description

The directory must first exist in order to be deleted, if the original is not a directory to the directory created
if not os.path.isdir (tarDir): os.makedirs (tarDir)

Guess you like

Origin blog.csdn.net/sinat_40624829/article/details/90315692