python3 处理txt,doc,docx,xls,xlsx文件

整理于2020年10月下旬,献给不甘平凡的你

更多python3基础知识请查收于:https://blog.csdn.net/weixin_45316122/article/details/109843899

 

一.xls文件和xlsx文件

  1. 使用xlrd模块读取excel文件,使用xlwt模块将数据写入excel文件,使用openpyxl模块读取写入和修改excel文件。
  2. 使用pandas更为快速

Trick:抱歉,此处写的只是简单方法,还有很多细节 没写清楚 ,没写清楚的部分请查看:

基于xlrd、xlwt和openpyxl模块 :https://blog.csdn.net/sinat_28576553/article/details/81275650

基于pandas写法:https://blog.csdn.net/dcrmg/article/details/88353004

 

二.doc文件和docx文件T

使用python-docx模块处理word文档,处理方式是面向对象的。也就是说python-docx模块会把word文档,文档中的段落、文本、字体等都看做对象,对对象进行处理就是对word文档的内容处理。(注意doc文件得转换成docx)

部分代码如下:

import docx
from win32com import client as wc
      # 获取文档
                    doc_content = requests.get(url)
                    with open('D:\爬虫下载\doc\\' + file_name, 'wb') as f:
                        f.write(doc_content.content)
                    print("转换doc开始")
                    word = wc.Dispatch("Word.Application")
                    doc = word.Documents.Open("D:\爬虫下载\doc\\" + file_name)
                    print("转换doc成功")
                    doc.SaveAs("D:\爬虫下载\docx\\" + file_name, 16)
                    doc.Close()
                    word.Quit()
                   ___________________________
                    doc = docx.Document('D:\爬虫下载\docx\\' + file_name)

                    for num in range(0, len(doc.tables)):
                        begin = 0 if num != 0 else 1
                        for row in range(begin, len(doc.tables[num].rows)):
                            title_list = []
                            data_list = []
                            for col in range(0, doc.tables[num]._column_count):
                                label_str = doc.tables[0].cell(0, col).text.replace('\n', '').replace(' ', '')
                                values = doc.tables[num].cell(row, col).text.replace('\n', '').replace(' ', '')

三.读取txt文件

file = open('E:\\个人文件\\6-desktop\\new.txt','r')
for line in file:
    print(line)

Trick:抱歉,此处写的只是简单遍历,还有很多细节 比如read()、readline()、readlines() 没写清楚 ,没写清楚的部分请查看https://blog.csdn.net/qq_37828488/article/details/100024924

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值