- 帖子
- 7
- 精华
- 0
- 积分
- 52
- 阅读权限
- 20
- 注册时间
- 2020-10-14
- 最后登录
- 2020-11-2
|
- import os
- import chardet
- def match(search_path,match_text):
- result_list = []
- for root, dirs, files in os.walk(search_path):
- # 遍历所有的文件
- for file in files:
- # 判断文件名是否以“.txt”结尾
- if file.endswith(".txt"):
- # 获取文件的绝对路径
- file_path = os.path.join(root,file)
- # print(file_path)
- # 判断文件的编码格式
- with open(file_path, "rb") as obj1:
- text_b = obj1.read()
- text_encoding = chardet.detect(text_b)["encoding"]
- # print(text_encoding)
- # 用指定的编码格式打开文件,判断文本参数是否存在于文件内容
- with open(file_path, "r", encoding=text_encoding) as obj2:
- text = obj2.read()
- if match_text in text:
- result_list.append(file_path)
- return result_list
- if __name__ == "__main__":
- # 提示用户输入路径
- while True:
- search_path = input("请输入搜索路径: ").strip()
- # 判断路径是否存在
- if os.path.exists(search_path):
- break
- print("路径不存在!")
- # 提示用户输入匹配的文字
- match_text = input("请输入匹配的文字: ")
- file_list = match(search_path,match_text)
- # 展示匹配到的文件
- print("匹配到的文件如下: ")
- for one in file_list:
- print(one)
复制代码 |
|