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()
4

1 回答 1

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.

于 2013-09-12T01:29:23.290 回答