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.