操作文件
操作Excel
环境搭建
pip install pandas openpyxl openpyxl
读取和保存
- 下载 pip install openpyxl
- 创建工作簿对象 openpyxl.Workbook()
- 获取活动工作表对象,wb.active
- 获取单元格 sheet
- 向单元格中写入数据,cell.value=值
- 想Excel中写入一行数据 sheet.append(列表)
- 保存Excel文件 wb.save(文件)
import pandas
data = pandas.read_excel("./response/03 Excel/附件:学院2023届毕业生毕业资格审核结果.xlsx")
write = pandas.ExcelWriter("./response/03 Excel/学院2023届毕业生毕业资格审核结果.xlsx")
data.to_excel(write, sheet_name="原来数据")
write.close()
data = pandas.read_excel("./response/03 Excel/附件:学院2023届毕业生毕业资格审核结果.xlsx")
print(data.keys())
读取Excel
import openpyxl
wb = openpyxl.load_workbook("./response/03 Excel/13 操作Excel第二种方式.xlsx")
Sheet = wb.active
cell = Sheet["A1"]
value = cell.value
print(value)
columns = Sheet["A"]
for item in columns:
print(item.value, end=",")
pass
row = Sheet[3]
print()
for item in row:
print(item.value, end=",")
pass
print()
clos = Sheet["B:S"]
for item in clos:
for cell in item:
print(cell.value, end=",")
openpyxl
import openpyxl
"""
- 下载 pip install openpyxl
- 创建工作簿对象 openpyxl.Workbook()
- 获取活动工作表对象,wb.active
- 获取单元格 sheet
- 向单元格中写入数据,cell.value=值
- 想Excel中写入一行数据 sheet.append(列表)
- 保存Excel文件 wb.save(文件)
"""
wb = openpyxl.Workbook()
sheet = wb.active
cell = sheet["A1"]
cell.value = "凌艳"
list = ["姓名", "年龄", "好看?"]
cell = sheet["A1"]
sheet.append(list)
list_list = [
["凌艳", "16", "好看"],
["陈晓晴", "16", "好看"],
["饶润婷", "16", "好看"],
["舒纹", "16", "好看"],
]
for item in list_list:
sheet.append(item)
wb.create_sheet("A1")
wb.save("./response/03 Excel/13 操作Excel第二种方式.xlsx")
操作CSV
import csv
with open("./response/csv/student.csv", "a+", newline="", encoding="utf-8") as File:
wirter = csv.writer(File)
wirter.writerow(["路由", "123"])
wirter.writerows([
["q", "123"],
["w", "123"],
["w", "123"],
["e", "123"],
])
压缩和解压
import shutil
shutil.make_archive(base_name=r"newZip", format="zip", root_dir="response/BeautifulSoup")
shutil.unpack_archive(filename="newZip.zip", extract_dir="./", format="zip")