Search code examples
pythonunicodedirectorypython-os

Various errors while scanning for folders


Please do not mark as duplicate as I have looked at the other questions with this error and I still can't figure it out.

I am making a basic scanner that scans a directory given to it and it deletes all sub directories that are older than 90 days. Here is the code:

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' 

Here is the full traceback:

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

Edit: When I use my program on a folder with multiple sub folders such as the desktop folder, it gives me the following error: WindowsError: [Error 2] The system cannot find the file specified and the name of the first folder.

I am using python 2.7.13. Can anyone please help? Any help is widely appreciated.


Solution

  • os.walk returns a 3-tuple (dirpath, dirnames, filenames). Your current approach iterates on the 3-tuple which in the second iteration gives a list of directory names dirnames.

    However, you are only interested in the dirnames:

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