這篇文章主要介紹了Python3實現從指定路徑查找文件的方法,涉及Python目錄與文件的相關操作技巧,需要的朋友可以參考下
本文實例講述了Python3實現從指定路徑查找文件的方法。分享給大家供大家參考。具體實現方法如下:
這里給定一個搜索路徑,根據這個路徑請求和請求的文件名,找到第一個符合要求的文件
- import os
- def search_file(file_name, search_path, pathsep = os.pathsep):
- for path in search_path.split(pathsep):
- candidate = os.path.join(path, file_name)
- if os.path.isfile(candidate):
- return os.path.abspath(candidate)
- return None
- search_path = 'd://pm//pm'
- find_file = search_file('babyos.img', search_path)
- if find_file:
- print("File 'babyos.img' found at %s" % find_file)
- else:
- print("File 'babyos.img' not found")
希望本文所述對大家的Python3程序設計有所幫助。
新聞熱點
疑難解答