現在のディレクトリとそのサブフォルダーで特定のファイルの最初のインスタンスを検索し、相対パスを文字列として返す関数を作成しようとしています。
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 を使用しています。