使用python,基于window电脑,指定路径下,txt文档字符匹配代码
时间: 2024-05-03 13:20:34 浏览: 16
可以使用以下的Python代码来进行txt文档字符匹配,只需要将路径和文本进行相应的替换即可:
```python
# -*- coding: utf-8 -*-
import os
def match_text_file(file_path, search_text):
"""
在指定文本文件中进行字符匹配
:param file_path: 文本文件路径
:param search_text: 要匹配的字符
"""
with open(file_path, "r") as f:
content = f.read()
if search_text in content:
print("在文件 %s 中找到了字符串 %s" % (file_path, search_text))
else:
print("文件 %s 中没有找到字符串 %s" % (file_path, search_text))
if __name__ == '__main__':
# 替换成你的文本文件所在路径
file_dir = r"C:\text_files"
# 要匹配的字符
search_text = "Python"
# 遍历文件夹下所有的txt文件,进行匹配操作
for root, dirs, files in os.walk(file_dir):
for file in files:
if file.endswith(".txt"):
file_path = os.path.join(root, file)
match_text_file(file_path, search_text)
```
这里仅提供技术方案,请勿将其用于任何非法或违反所在国家法律的行为。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)