Python 读写word、csv、xlsx

1、读写word

import win32com.client
path =r'C:\Users\aeasringnar\Desktop\test.doc'
#调用系统模块
word=win32com.client.Dispatch("Word.Application")#系统模块的使用
doc=word.Documents.Open(path)#打开文件
for i in doc.Paragraphs:  #进行读取
    print(i)

2、读写csv

import csv #调用系统方法
path=r'C:\Users\aeasringnar\Desktop\000001.csv'
def readCsv(path):
    mylist=[]
    with open(path,'r') as f: #打开文件,跟open类似
        info=csv.reader(f) #读文件,并给一个变量
        for i in info:     #将每一行遍历出来,
            mylist.append(i) #添加到列表里
    return mylist
print(readCsv(path))
mylist=[[1,2,3],[4,5,6]]
def writeCsv(path,mylist):
    with open(path,'w') as f:#读取文件
        write=csv.writer(f)
        for i in mylist:
            print('row=',i)
            write.writerow(i)
writeCsv(path,mylist)

3、读写xlsx

from openpyxl.reader.excel import load_workbook
path='1.xlsx'
#读取单一表格
file=load_workbook(filename=path)
table=file.get_sheet_names()#获取所有表格的名称
#拿出第一个表格的名称
# print(table[0])
anlibofa=file.get_sheet_by_name(table[0])
# print(anlibofa.max_row)  #获取第一个表格的最大行数
# print(anlibofa.max_column) #获取最大列数
for line in range(1,anlibofa.max_row+1):
    mylist=[]#建立一个空列表来存储数据,
    for col in range(1,anlibofa.max_column+1):
        cal=anlibofa.cell(row=line,column=col).value#根据行和列进行取值
        mylist.append(cal)#将数据添加到 新的列表中
    print(mylist)

from collections import OrderedDict
from pyexcel_xls import save_data
path = r"C:\Users\xlg\Desktop\2222.xls"
data = {"表一":[[1,2,3],[1,2,3],[1,2,3]],"表二":[[4,5,6],[7,8,9],[1,2,3]]}
dic = OrderedDict()
#data.items() 返回一个可遍历的字典 返回 键值对
for name,value in data.items():
    d = {}
    d[name] = value
    dic.update(d)
save_data(path,dic)

你可能感兴趣的:(Python,python,读写word,读写csv,读写xlsx)