我正在尝试编写一个函数,该函数在当前目录及其子文件夹中查找特定文件的第一个实例,并将相对路径作为字符串返回。
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
当我这样调用函数时:
csvPath = findFirstMatch('bounding_box_limits.csv')
在 Python 控制台中运行时收到此错误消息:
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']"
它找到了文件,但是所有这些额外的反斜杠是如何在文件路径中结束的呢?
注意:我使用的是 Windows 7 和 Python 2.7.3。