打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
python 查找文件名包含指定字符串的方法

编写一个程序,能在当前目录以及当前目录的所有子目录下查找文件名包含指定字符串的文件,并打印出绝对路径。

  1. import os
  2. class SearchFile(object):
  3.      def __init__(self,path='.'):
  4.      self._path=path
  5.      self.abspath=os.path.abspath(self._path) # 默认当前目录
  6.      def findfile(self,keyword,root):
  7.      filelist=[]
  8.      for root,dirs,files in os.walk(root):
  9.      for name in files:
  10.      fitfile=filelist.append(os.path.join(root, name))
  11.      #print(fitfile)
  12.      print(os.path.join(root, name))
  13.      #print(filelist)
  14.      print('...........................................')
  15.      for i in filelist:
  16.      if os.path.isfile(i):
  17.      #print(i)
  18.      if keyword in os.path.split(i)[1]:
  19.      print('yes!',i) # 绝对路径
  20.      #else:
  21.      #print('......no keyword!')
  22.      def __call__(self):
  23.      while True:
  24.      workpath=input('Do you want to work under the current folder? Y/N:')
  25.      if(workpath == ''):
  26.      break
  27.      if workpath=='y' or workpath=='Y':
  28.      root=self.abspath # 把当前工作目录作为工作目录
  29.      print('当前工作目录:',root)
  30.      dirlist=os.listdir() # 列出工作目录下的文件和目录
  31.      print(dirlist)
  32.      else:
  33.      root=input('please enter the working directory:')
  34.      print('当前工作目录:',root)
  35.      keyword=input('the keyword you want to find:')
  36.      if(keyword==''):
  37.      break
  38.      self.findfile(keyword,root) # 查找带指定字符的文件
  39. if __name__ == '__main__':
  40.      search = SearchFile()
  41.      search()

运行结果:

注意:在运行的时候如果选择y,也就是把.py文件所在的目录作为工作目录,此时最好不要把.py文件放到桌面上,因为会遍历桌面上的所有目录及目录下的所有文件,会很大。

以上这篇python 查找文件名包含指定字符串的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

本文标题: python 查找文件名包含指定字符串的方法
本文地址: http://www.cppcns.com/jiaoben/python/229619.html
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
C# 获取文件名及扩展名
find 命令:查找文件
VB.NET System.IO.Path 文件名、路径、扩展名 处理
python os模块 读写、创建 文件
[快学Python3]目录与文件操作
盘点Python中os模块的那些用法
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服