设为首页收藏本站

Crossin的编程教室

 找回密码
 立即加入
楼主: crossin先生
打印 上一主题 下一主题

【每日一坑 6】 查找文件内容

[复制链接]

0

主题

0

好友

52

积分

注册会员

Rank: 2

楼主
发表于 2020-10-14 23:22:50 |显示全部楼层
  1. import os
  2. import chardet

  3. def match(search_path,match_text):
  4.     result_list = []

  5.     for root, dirs, files in os.walk(search_path):
  6.         # 遍历所有的文件
  7.         for file in files:
  8.             # 判断文件名是否以“.txt”结尾
  9.             if file.endswith(".txt"):

  10.                 # 获取文件的绝对路径
  11.                 file_path = os.path.join(root,file)
  12.                 # print(file_path)

  13.                 # 判断文件的编码格式
  14.                 with open(file_path, "rb") as obj1:
  15.                     text_b = obj1.read()
  16.                     text_encoding = chardet.detect(text_b)["encoding"]
  17.                     # print(text_encoding)

  18.                 # 用指定的编码格式打开文件,判断文本参数是否存在于文件内容
  19.                 with open(file_path, "r", encoding=text_encoding) as obj2:
  20.                     text = obj2.read()
  21.                     if match_text in text:
  22.                         result_list.append(file_path)

  23.     return result_list


  24. if __name__ == "__main__":

  25.     # 提示用户输入路径
  26.     while True:
  27.         search_path = input("请输入搜索路径: ").strip()
  28.         # 判断路径是否存在
  29.         if os.path.exists(search_path):
  30.             break
  31.         print("路径不存在!")
  32.     # 提示用户输入匹配的文字
  33.     match_text = input("请输入匹配的文字: ")
  34.     file_list = match(search_path,match_text)
  35.     # 展示匹配到的文件
  36.     print("匹配到的文件如下: ")
  37.     for one in file_list:
  38.         print(one)
复制代码

result.png (7.75 KB, 下载次数: 397)

result.png

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即加入

QQ|手机版|Archiver|Crossin的编程教室 ( 苏ICP备15063769号  

GMT+8, 2024-5-3 12:00 , Processed in 0.025570 second(s), 26 queries .

Powered by Discuz! X2.5

© 2001-2012 Comsenz Inc.

回顶部