如何在Python中删除本地文件夹的内容?

目前的项目是Windows,但我也想看到*nix。


当前回答

回答一个有限的、具体的情况: 假设你想在维护子文件夹树的同时删除文件,你可以使用递归算法:

import os

def recursively_remove_files(f):
    if os.path.isfile(f):
        os.unlink(f)
    elif os.path.isdir(f):
        for fi in os.listdir(f):
            recursively_remove_files(os.path.join(f, fi))

recursively_remove_files(my_directory)

也许有点跑题,但我想很多人会觉得它很有用

其他回答

作为一个在线人士:

import os

# Python 2.7
map( os.unlink, (os.path.join( mydir,f) for f in os.listdir(mydir)) )

# Python 3+
list( map( os.unlink, (os.path.join( mydir,f) for f in os.listdir(mydir)) ) )

一个更健壮的文件和目录的解决方案是(2.7):

def rm(f):
    if os.path.isdir(f): return os.rmdir(f)
    if os.path.isfile(f): return os.unlink(f)
    raise TypeError, 'must be either file or directory'

map( rm, (os.path.join( mydir,f) for f in os.listdir(mydir)) )

删除文件夹a中的所有文件:

import os
for i in os.listdir():
    os.remove(i)
import os, shutil
folder = '/path/to/folder'
for filename in os.listdir(folder):
    file_path = os.path.join(folder, filename)
    try:
        if os.path.isfile(file_path) or os.path.islink(file_path):
            os.unlink(file_path)
        elif os.path.isdir(file_path):
            shutil.rmtree(file_path)
    except Exception as e:
        print('Failed to delete %s. Reason: %s' % (file_path, e))

使用这个函数

import os
import glob

def truncate(path):
    files = glob.glob(path+'/*.*')
    for f in files:
        os.remove(f)

truncate('/my/path')

我觉得这个密码起作用了。它不会删除文件夹,您可以使用此代码删除具有特定扩展名的文件。

import os
import glob

files = glob.glob(r'path/*')
for items in files:
    os.remove(items)