python实践 将多个文本合并为一个文本

您所在的位置:网站首页 Python读取TXT python实践 将多个文本合并为一个文本

python实践 将多个文本合并为一个文本

2023-06-06 21:03| 来源: 网络整理| 查看: 265

思路

首先运用os模块获得多个文本的名称。然后,运用相关包读取这些文件,并汇集在一起。

实践:word文件

将多份在百度网盘中的word文件,合并在一起。代码如下:

import docx import os wfile=open("result.txt","w",encoding="utf-8") os.chdir("E:\eng") subList=os.listdir(os.getcwd())#总的eng文件夹。 for inum in subList: os.chdir(f"E:\eng\{inum}")#eng文件夹中的子文件夹。 inumList=os.listdir(os.getcwd()) for idocx in inumList: print(f"文章{idocx}",file=wfile) ifile=docx.Document(f"{idocx}") for p in ifile.paragraphs: line=p.text print(line,file=wfile) print("\n",file=wfile) wfile.close()

解析如下:

第一步,将百度网盘中的文件下载在电脑上(以下载后的eng文件夹为例,eng文件夹中包含很多子文件夹),和程序文件放在一起(以test.py为例)。

import os os.chdir("E:\eng") subList=os.listdir(os.getcwd())#总的eng文件夹。 for inum in subList: os.chdir(f"E:\eng\{inum}")#eng文件夹中的子文件夹。 inumList=os.listdir(os.getcwd()) print(inumList)

第二步,打开程序包docx,如果没有安装,就用pip安装

pip install python-docx

然后会显示安装成功。

第三步,调用docx包去读取docx文件。

for inum in subList: os.chdir(f"E:\eng\{inum}")#eng文件夹中的子文件夹。 inumList=os.listdir(os.getcwd()) for idocx in inumList: print(f"文章{idocx}",file=wfile)#便于区分各个文件 ifile=docx.Document(f"{idocx}")#使用docx包读取文件 for p in ifile.paragraphs: line=p.text print(line,file=wfile)#把文件输入wfile文档中 print("\n",file=wfile)

第四步,最后把生成的txt文本,复制粘贴到docx文本中,就可以完成。

当然,可以将代码进一步优化。比如,用docx包生成word,而不是生成txt。如下:

import docx import os from docx import Document#创建document对象,即打开一个word 文档 mydocument=Document() myp=mydocument.add_paragraph(" ") os.chdir("E:\eng") subList=os.listdir(os.getcwd())#总的eng文件夹。 for inum in subList: os.chdir(f"E:\eng\{inum}")#eng文件夹中的子文件夹。 inumList=os.listdir(os.getcwd()) for idocx in inumList: mydocument.add_heading(f"文章{idocx}",level=0) ifile=docx.Document(f"{idocx}")#使用docx包读取文件 for p in ifile.paragraphs: line=p.text myp.add_run(line)#把段落添加入文件 myp.add_run("\n") mydocument.save("resulteng.docx")

但是在实践过程中,这段代码没有成功。优化功能没有实现。之后需要补充docx包相关的知识,然后去解决这个问题。

实践:excel文件

生成多份excel文件,并将这些文件合并在一起。代码如下:

import os from random import choice,randrange from random import * from openpyxl import Workbook,load_workbook import sqlite3 def GRD(): for i in range(10): xlsName="xlsxs"+str(i)+".xlsx" totalLines=randrange(100) wb=Workbook() ws=wb.worksheets[0] ws.append(["a","b","c","d","e"]) for j in range(totalLines): line=[chr(randint(50,70)) for x in range(5) ] ws.append(line) wb.save(xlsName) GRD() print(os.getcwd()) os.chdir("E:\社团") print(os.listdir(os.getcwd())) xlsxs=("xlsxs"+ fn for fn in os.listdir(".")) with sqlite3.connect("dataxlsx.db") as conn: cur=conn.cursor() for xlsx in xlsxs: sql="INSERT INFO fromxlsx VALUE(?,?,?,?,?)" cur.executemany(sql,eachXlsx(xlsx)) conn.commit()



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3