遍历一个文件夹下的所有txt文件,并将每一个txt作为一行保存到excel中
时间: 2024-05-06 07:17:51 浏览: 21
可以使用Python中的os和openpyxl模块来实现。
首先,使用os模块遍历文件夹,找到所有的txt文件,然后读取每个txt文件的内容。接着,使用openpyxl模块创建一个新的Excel文件,并将每个txt文件的内容写入Excel文件中的一行。最后保存Excel文件。
下面是实现代码:
```python
import os
import openpyxl
# 遍历文件夹,找到所有的txt文件
def get_txt_files(folder):
txt_files = []
for file_name in os.listdir(folder):
file_path = os.path.join(folder, file_name)
if os.path.isfile(file_path) and file_name.endswith('.txt'):
txt_files.append(file_path)
return txt_files
# 读取txt文件的内容
def read_txt_file(file_path):
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
return content.strip()
# 将txt文件的内容写入Excel文件中的一行
def write_to_excel(worksheet, row, content):
worksheet.cell(row=row, column=1, value=content)
# 创建Excel文件
def create_excel_file(file_path):
workbook = openpyxl.Workbook()
worksheet = workbook.active
worksheet.title = 'Txt Files'
return workbook, worksheet
# 保存Excel文件
def save_excel_file(workbook, file_path):
workbook.save(file_path)
if __name__ == '__main__':
# 设置文件夹路径和Excel文件路径
folder = './txt_files'
excel_file_path = './txt_files.xlsx'
# 获取所有的txt文件
txt_files = get_txt_files(folder)
# 创建Excel文件
workbook, worksheet = create_excel_file(excel_file_path)
# 将每个txt文件的内容写入Excel文件中的一行
for i, txt_file in enumerate(txt_files):
content = read_txt_file(txt_file)
write_to_excel(worksheet, i+1, content)
# 保存Excel文件
save_excel_file(workbook, excel_file_path)
```
在上述代码中,文件夹路径和Excel文件路径可以根据实际情况进行修改。此外,还需要注意Excel文件中的行数与txt文件的数量一致,因此在写入Excel文件时需要使用enumerate函数来记录行数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)