Created
October 18, 2020 13:29
-
-
Save ixuuux/41894a23489a0898b8c8e85d49721c56 to your computer and use it in GitHub Desktop.
删除任意文件/文件夹。非空文件夹依然可以正确删除。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import os | |
def remove_any_dir_file(dir_or_file_path: str) -> None: | |
""" 删除任意文件/文件夹。非空文件夹依然可以正确删除。 | |
例如: | |
>>> import os | |
>>> dir_path = os.path.join(os.getcwd(), 'test') | |
>>> dir_path | |
'E:\\Xuzh\\test' | |
>>> # 调用本方法 | |
>>> remove_any_dir_file(dir_or_file_path=dir_path) | |
>>> # 结束,本方法没有返回值 | |
:param dir_or_file_path: 文件/文件夹路径,建议使用`os.path.join()`进行拼接 | |
:return: None | |
""" | |
is_dir = os.path.isdir(dir_or_file_path) | |
if is_dir: | |
file_list = os.listdir(dir_or_file_path) | |
# 空文件夹直接删除 | |
if len(file_list) == 0: | |
return os.rmdir(dir_or_file_path) | |
# 遍历递归 | |
for dor_path in file_list: | |
dor_path = os.path.join(dir_or_file_path, dor_path) | |
remove_any_dir_file(dir_or_file_path=dor_path) | |
else: | |
os.remove(dir_or_file_path) | |
# 确保传入的文件夹可以删掉 | |
try: | |
os.rmdir(dir_or_file_path) | |
except FileNotFoundError: | |
... | |
if __name__ == '__main__': | |
remove_any_dir_file(os.path.join(os.getcwd(), 'test')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment