帮我用python写一个从50个txt文本中提取第五行和第7行的数据,并让这两组数据一一对应生成一个excel表格
时间: 2024-05-08 07:18:55 浏览: 21
好的,很高兴为您提供帮助!以下是代码实现:
```python
import os
import csv
# 指定文件夹路径
folder_path = '/path/to/text/files'
# 遍历文件夹中的所有txt文件并提取数据
data = []
for filename in os.listdir(folder_path):
if filename.endswith('.txt'):
file_path = os.path.join(folder_path, filename)
with open(file_path, 'r', encoding='utf-8') as f:
lines = f.readlines()
# 确保文件中包含第5行和第7行数据
if len(lines) >= 7:
data.append((lines[4].strip(), lines[6].strip()))
# 生成Excel表格
with open('data.csv', 'w', encoding='utf-8', newline='') as f:
writer = csv.writer(f)
writer.writerow(['第5行', '第7行'])
writer.writerows(data)
```
请确保将“/path/to/text/files”替换为您实际的文本文件夹路径。此外,Python中有多种方法可以处理和生成Excel文件,这里使用了CSV库作为示例。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![xlsx](https://img-home.csdnimg.cn/images/20210720083732.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![xlsx](https://img-home.csdnimg.cn/images/20210720083732.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)