Question

I'm trying to write a function that finds the first instance of a particular file in the current directory and its subfolders, and returns the relative path as a string.

def findFirstMatch(targetFile):
    try:
        fileMatched = []
        for root, dirnames, filenames in os.walk('.'):
            for filename in fnmatch.filter(filenames, targetFile):
                fileMatched.append(os.path.join(root, filename))
            if len(fileMatched) != 0:
                fileMatched = str(fileMatched)
                return fileMatched
        if len(fileMatched) == 0:
            raise NotFoundError, 'File could not be found.'
    except NotFoundError, error:
        print error

When I call the function like so:

csvPath = findFirstMatch('bounding_box_limits.csv')

I get this error message when running in the Python console:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "MassSpringDamperCAD.py", line 121, in <module>
    main()
  File "MassSpringDamperCAD.py", line 90, in main
    with open(csvPath, 'r') as csvFile:
IOError: [Errno 2] No such file or directory: "['.\\\\common\\\\bounding_box_limits.csv']"

It found the file, but how did all those extra backslashes end up in the file path?

Note: I am using Windows 7, and Python 2.7.3.

Was it helpful?

Solution

These backslashes are side effect of the fact that they're backslashes. Gobbledygook :-)

In strings, the backslash to mean backslash is often preceded by backslash in CLI, otherwise in precedes special character synonym, like \n for newline, \t for tab. From my experience the number of these backslashes does not cause problems. You can always try to normalize the path in string by os.path.normpath().

This problem is certainly Windows specific.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top