0

I am running a script that attempts to recursively run through a folder of files and count how many of the given file types there are. It works swimmingly when there are no SPACES in the folder name. Why is this? What is a good way to fix this? Thank you!

import os
import fnmatch

def getPath():
    path = raw_input("Drag file/enter filepath here: ")
    return path

def convert():

    patterns = ['*.wav', '*.aif', '*.aiff', '*.flac', '*.alac']
    count = 0

    for index in patterns:
        for root, dirs, files in os.walk(rootPath):
            for filename in fnmatch.filter(files, index):
                inputName = os.path.join(root, filename)
                print inputName
                count = count + 1

    print count


rootPath = getPath()
convert()
ianks
  • 1,478
  • 14
  • 14
  • 1
    No, that's not the problem you're having. – Ignacio Vazquez-Abrams Sep 11 '13 at 23:54
  • Where does `outputName` come from? You should consider using parameters to your function instead of using globals. And walking the whole directory tree once for each extension in the list seems a bit extensive, you should swich the order of your loops. Other then that - it should work. – mata Sep 12 '13 at 00:05
  • sorry, forgot to take output name out. fixed now. but no, it is not working (at least on Mac). it will go through a folder of *.wavs, etc and count them correctly if there is no SPACE in the folder name. otherwise it will not. does it work for you guys as is? – ianks Sep 12 '13 at 00:10
  • also, thanks for the advice mata. i am fairly new to this so i'm trying to grasp exactly whats happening. i will look into changing the order of the for loops as well. – ianks Sep 12 '13 at 00:11

1 Answers1

1

Try the solution in this other question. Define another function:

def shellquote(s):
    return "'" + s.replace("'", "'\\''") + "'"

Then, when you've captured path within getPath(), do

new_path = shellquote(path)

and return new_path instead of path.

When you drag the file in or write a path with spaces, you need to either escape the spaces or put the whole path in quotes so it's clear that it's one single string. The shellquotes() function achieves both.

Community
  • 1
  • 1
arturomp
  • 26,187
  • 10
  • 39
  • 64