python遍历目录查找文件并读取文件
时间: 2023-12-12 22:31:15 浏览: 69
可以使用os模块中的walk函数遍历目录,使用open函数读取文件内容。具体代码如下:
```python
import os
def read_files(path):
for root, dirs, files in os.walk(path):
for file in files:
file_path = os.path.join(root, file)
with open(file_path, 'r') as f:
content = f.read()
# 处理文件内容
print(content)
# 示例:遍历当前目录下所有文件并读取内容
read_files('.')
```
相关问题
python遍历文件找列表中对应的项
你可以使用Python中的`os`模块进行文件遍历,使用`os.listdir()`函数获取当前目录下所有文件和文件夹的列表,然后对每个文件进行判断,如果是文件夹则递归进行遍历,如果是文件则打开文件进行读取,使用`in`操作符判断列表中是否包含特定项。以下为示例代码:
```
import os
def search_file(data_list, target):
file_list = os.listdir('.')
for file in file_list:
if os.path.isdir(file):
search_file(data_list, target)
else:
with open(file) as f:
for line in f:
if target in line:
print(f'{target} found in {file}')
# 示例列表和目标项
data_list = ['apple', 'banana', 'orange', 'pear']
target = 'orange'
search_file(data_list, target)
```
上述代码将会在当前目录下进行遍历,查找目标列表中是否包含`orange`项,如果找到了则打印出该项在哪个文件中被找到。
python 文读取目录下的指定后缀文件
可以使用 `os` 模块来读取目录下的文件,然后使用字符串的 `endswith` 方法来判断文件的后缀是否满足要求。
以下是一个示例代码:
```python
import os
# 指定目录路径和需要查找的文件后缀
dir_path = '/path/to/directory'
file_ext = '.txt'
# 遍历目录下的所有文件和子目录
for root, dirs, files in os.walk(dir_path):
for file in files:
# 判断文件后缀是否满足要求
if file.endswith(file_ext):
# 如果满足要求,则打印文件路径
file_path = os.path.join(root, file)
print(file_path)
```
在上面的示例中,`os.walk` 方法会递归地遍历指定目录下的所有文件和子目录,返回一个三元组 `(root, dirs, files)`,其中 `root` 是当前目录的路径,`dirs` 是当前目录下的子目录列表,`files` 是当前目录下的文件列表。我们可以遍历 `files` 列表,对于每个文件,使用字符串的 `endswith` 方法来判断其后缀是否为指定的后缀。如果满足要求,则使用 `os.path.join` 方法来拼接文件路径,并打印出来。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)