我正在编写一些Python代码。我想在程序结束时删除new_folder
以及其中的所有文件。
有人可以指导我如何做吗?我看到过不同的命令,如os.rmdir,但它只会删除路径。以下是我的代码:
for files in sorted(os.listdir(path)):
os.system("mv "+path+" new_folder")`
上面的代码将移动一个名为check的文件夹到new_folder中。我想从new_folder中删除该check文件夹。
我正在编写一些Python代码。我想在程序结束时删除new_folder
以及其中的所有文件。
有人可以指导我如何做吗?我看到过不同的命令,如os.rmdir,但它只会删除路径。以下是我的代码:
for files in sorted(os.listdir(path)):
os.system("mv "+path+" new_folder")`
上面的代码将移动一个名为check的文件夹到new_folder中。我想从new_folder中删除该check文件夹。
如果您想要删除该文件
import os
os.remove("path_to_file")
但是使用上面的代码无法删除目录,如果想要删除目录,请使用以下代码
但你不能使用上面的代码来删除目录,如果想要删除目录,则使用以下代码
import os
os.rmdir("path_to_dir")
从上面的命令中,如果目录为空,则可以删除目录,如果目录不为空,则可以使用shutil模块。import shutil
shutil.rmtree("path_to_dir")
以上所有方法都是Python的方式。如果您了解您的操作系统,那么这种方法取决于操作系统,所有上述方法都不会受到影响。
import os
os.system("rm -rf _path_to_dir")
这是我的方法:
# function that deletes all files and then folder
import glob, os
def del_folder(dir_name):
dir_path = os.getcwd() + "\{}".format(dir_name)
try:
os.rmdir(dir_path) # remove the folder
except:
print("OSError") # couldn't remove the folder because we have files inside it
finally:
# now iterate through files in that folder and delete them one by one and delete the folder at the end
try:
for filepath in os.listdir(dir_path):
os.remove(dir_path + "\{}".format(filepath))
os.rmdir(dir_path)
print("folder is deleted")
except:
print("folder is not there")
使用 os.system("rm -rf" + 某个路径 +" 新文件夹")
shutil.rmtree
。如果字符串whatever_path
来自不受信任的输入,则此答案打开了执行任意shell命令的可能性。 - Odysseas