如何使用python删除文件夹中的所有文件夹?

2024-09-29 19:21:41 发布

您现在位置:Python中文网/ 问答频道 /正文

是否可以删除文件夹中的所有文件夹而不使用特定路径?,在这里我移动文件的内容,然后我想删除,如果它是一个目录

import os, zipfile
import shutil
import os
from os import path


dir_name = 'C:\\Users\\Guest\\Desktop\\OJT\\samples'
destination = 'C:\\Users\\Guest\\Desktop\\OJT\\scanner\\test'
for path, subdirs, files in os.walk(destination):
    for name in files:
        filename = os.path.join(path, name)
        shutil.copy2(filename, destination)

Tags: pathnameinimport文件夹forosfiles
3条回答

正如前面@Vineeth Sai所建议的,如果要删除目录中的所有子目录,只需使用^{}遍历每个文件,如果文件是目录,则应用^{}

from os import listdir

from os.path import abspath
from os.path import isdir
from os.path import join

from shutil import rmtree

path = 'YOUR PATH HERE'

for file in listdir(path):
    full_path = join(abspath(path), file)

    if isdir(full_path):
        rmtree(full_path)

上面还使用^{}检查文件是否是目录。你知道吗

是的,使用shutil的rmtree方法。你知道吗

import shutil 
shutil.rmtree('directory') # the directory you want to remove
os.listdir()

您也可以使用os.rmdir,但如果其中包含任何内容,则这将不起作用。你知道吗

如果要检查特定路径是否为目录,则可以使用os.path.isdir,然后运行rmtree,如果返回TRUE

如果您想保持文件夹完好无损,那么可以walk该目录并对每个项调用rmtree。你知道吗

如果Vineeth's答案不适合您的情况,您可以使用subprocess模块运行os特定的命令,如下所示

import subprocess
subprocess.call('rm -rf /path/of/the/dirctory/*', shell=True)

上面的命令是linux特定的,您可以使用上面相同命令的windows对应项。你知道吗

注意-这里shell=True*展开到文件/文件夹中。你知道吗

另外,注意Vineeth's答案是os独立的,上面的答案是os特定的。小心。你知道吗

另外,您还可以使用subprocess模块运行powershell命令。你知道吗

相关问题 更多 >

    热门问题