Python3实现从指定路径查找文件的方法

yipeiwu_com6年前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程序设计有所帮助。

相关文章

Python中关键字is与==的区别简述

本文以简单示例分析了python中关键字is与 ==的区别,供大家参考一下。 首先说明一下Python学习中几个相关的小知识点。 Python中的对象包含三要素:id、type、valu...

pandas中DataFrame修改index、columns名的方法示例

一般常用的有两个方法: 1、使用DataFrame.index = [newName],DataFrame.columns = [newName],这两种方法可以轻松实现。 2、使用...

浅谈Pandas中map, applymap and apply的区别

1.apply() 当想让方程作用在一维的向量上时,可以使用apply来完成,如下所示 In [116]: frame = DataFrame(np.random.randn(4,...

Python 正则表达式操作指南

原文作者:A.M. Kuchling (amk@amk.ca) 授权许可:创作共享协议 翻译人员:FireHare 校对人员:Leal 适用版本:Python 1.5 及后续版本http...

Python二叉树的遍历操作示例【前序遍历,中序遍历,后序遍历,层序遍历】

本文实例讲述了Python二叉树的遍历操作。分享给大家供大家参考,具体如下: # coding:utf-8 """ @ encoding: utf-8 @ author: lixia...