python - 扫描文件夹时出现各种错误

标签 python unicode directory python-os

请不要标记为重复,因为我已经查看了包含此错误的其他问题,但我仍然无法弄清楚。

我正在制作一个基本扫描仪,它扫描给定的目录,并删除所有超过 90 天的子目录。这是代码:

import os, sys
import time
import shutil
from  Tkinter import *
import Tkinter, Tkconstants, tkFileDialog



now = time.time()
home1 = os.path.join(os.environ["HOMEPATH"], "Desktop")
desktop = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')

root = Tk()
root.withdraw()
path = tkFileDialog.askdirectory(initialdir=desktop, title="Select folder to scan from: ")
path = path.encode('utf-8')

for x in os.walk(path):
    for folders in x:
        while os.stat(folders).st_mtime < now - 90 * 86400:
            q = raw_input('Folder(s) found. NOTE: This will delete all directories or subdirectories in the folder. Do you want to remove?(y/n) ')
            if str(q) == "y" or str(q) == "Y":
                shutil.rmtree(path, ignore_errors=True)
                print 'Successfully deleted folder(s)'
            elif str(q) == "n" or str(q) == "N":
                print 'Folders not deleted.'
                sys.exit()
        else:
            print 'No folder(s) over 90 days' 

这是完整的回溯:

Traceback (most recent call last):
File "C:/Users/Bill/Desktop/limitScanner/scanner.py", line 20, in <module>
while os.stat(folders).st_mtime < now - 90 * 86400:
TypeError: coercing to Unicode: need string or buffer, list found

编辑:当我在具有多个子文件夹的文件夹(例如桌面文件夹)上使用我的程序时,出现以下错误:WindowsError:[错误2]系统找不到指定的文件以及第一个文件夹的名称。

我正在使用python 2.7.13。有人可以帮忙吗?任何帮助都将受到广泛赞赏。

最佳答案

os.walk 返回一个三元组(dirpath, dirnames, filenames)。您当前的方法在 3 元组上迭代,在第二次迭代中给出目录名称 dirnames 的列表。

但是,您只对目录名感兴趣:

for _, dirs, _ in os.walk(path):
    for folder in dirs:
        ...

关于python - 扫描文件夹时出现各种错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44971692/

相关文章:

python - 使用 Python 的 HTTPBasicAuthHandler 进行 Bitbucket API 身份验证

python - 如何在布局中的小部件之间捕获 mousePressEvent?

Python - 'ascii' 编解码器无法解码字节

regex - 字符名称,替换和Umlaut “Ü”:格式错误的UTF-8字符

java - 如何使用 apache commons io 复制空目录?

基于 Python 的网络报告工具?

python - 将列表中的项目添加到python中的列表列表

函数内的 Python 2.7 Unicode 错误(使用 __future__ print_function 和 unicode_literals)

git - 如何在 git 中保留 DIRECTORY 文件模式或权限?

linux - 在工作目录(及其子目录)中搜索包含同一行字符串的文件