使用python循环遍历两个文件夹下的不同文本文件,按行读取文本文件数据,将想要的数据添加到列表里,然后打印列表
时间: 2024-05-12 17:18:18 浏览: 14
你可以使用以下代码来实现:
```python
import os
folder1 = 'path/to/folder1'
folder2 = 'path/to/folder2'
files1 = os.listdir(folder1)
files2 = os.listdir(folder2)
data = []
for file in files1:
if file.endswith('.txt'):
with open(os.path.join(folder1, file), 'r') as f:
lines = f.readlines()
for line in lines:
# 在这里添加你想要的条件,将符合条件的数据添加到列表中
data.append(line)
for file in files2:
if file.endswith('.txt'):
with open(os.path.join(folder2, file), 'r') as f:
lines = f.readlines()
for line in lines:
# 在这里添加你想要的条件,将符合条件的数据添加到列表中
data.append(line)
print(data)
```
你需要将 `path/to/folder1` 和 `path/to/folder2` 替换为你要遍历的文件夹的路径,然后调整 `if` 语句中的条件,将想要的数据添加到列表 `data` 中。最后,通过 `print(data)` 将列表中的数据打印出来。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.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)