Python从“result”文件夹中读取所有的txt文档,并且将每个txt文档中的每一行数据都读出来,然后写入excel表中,将excel以txt文档名称输出到result文件夹中
时间: 2024-09-11 15:19:09 浏览: 99
在Python中,你可以使用pandas库来处理这个任务。首先,确保已安装了`pandas`, `openpyxl`以及`os`模块。以下是完成此操作的步骤:
1. 导入库和模块:
```python
import os
import pandas as pd
from openpyxl import Workbook
```
2. 定义函数来读取txt文件并写入excel:
```python
def read_txt_to_excel(txt_files_dir, output_folder):
for filename in os.listdir(txt_files_dir):
if filename.endswith(".txt"):
with open(os.path.join(txt_files_dir, filename), 'r') as f:
lines = f.readlines()
# 创建一个空的工作簿
wb = Workbook()
ws = wb.active
# 将文本文件内容写入Excel
for i, line in enumerate(lines):
ws.cell(row=i+1, column=1, value=line.strip()) # 去除换行符并写入
# 写入Excel并设置文件名
excel_name = filename.replace('.txt', '.xlsx')
full_output_path = os.path.join(output_folder, excel_name)
wb.save(full_output_path)
# 调用函数
read_txt_to_excel('result', 'result')
```
这段代码会遍历result文件夹中的所有.txt文件,逐行读取,然后将内容写入一个新的Excel工作簿中,Excel文件名与原txt文件名相同,只是扩展名为.xlsx。
阅读全文
相关推荐


















