写入到csv表格
# 导入CSV安装包 import csv # 1. 创建文件对象 f = open(\'嘻嘻.csv\',\'w\',encoding=\'utf-8\',newline=\'\') # 2. 基于文件对象构建 csv写入对象 csv_writer = csv.writer(f) # 3. 构建列表头 csv_writer.writerow(["姓名","年龄","性别"]) # 4. 写入csv文件内容 csv_writer.writerow(["l",\'18\',\'男\']) csv_writer.writerow(["c",\'20\',\'男\']) csv_writer.writerow(["w",\'22\',\'女\']) # 5. 关闭文件 f.close()
读取csv表格
# 1. 创建文件对象 with open(\'嘻嘻.csv\',\'r\',encoding=\'utf-8\') as f: f_csv = csv.reader(f) #过滤掉标题 next(f_csv) #读取内容 for i in f_csv: print(i)
写入到Excel表格
import xlwt #创建Excel Excel_book = xlwt.Workbook() #创建sheet sheet = Excel_book.add_sheet(\'test\') #在一行一列写入文字‘hello’ sheet.write(1,0,\'hello\') Excel_book.save(\'test.xls\')
读取Excel表格
#读取Excel import xlrd data = xlrd.open_workbook(\'test.xls\') #获取第一个sheet sheet = data.sheets()[0] #获取行数和列数 nrows = sheet.nrows ncols = sheet.ncols #获取行数据 for i in range(nrows): print(sheet.row_values(i)) #获取列数据 for j in range(ncols): print(sheet.col_values(j))
写入到word(一般用不到)
#写入到Word from docx import Document document = Document() document.add_paragraph(\'hello,word\') document.save(\'demo.docx\')