import os
import sys
from pathlib import Path
import openpyxl # openpyxl引入模块
sys.path.append(Path(file).parent.resolve())
sys.path.append(Path(file).parent.parent.resolve())
sys.path.append(Path(file).parent.parent.parent.resolve())
def write_to_excel(path: str, sheetStr, info, data):
# 实例化一个workbook对象
workbook = openpyxl.Workbook()
# 激活一个sheet
sheet = workbook.active
# 为sheet设置一个title
sheet.title = sheetStr
# 添加表头(不需要表头可以不用加)
data.insert(0, list(info))
# 开始遍历数组
for row_index, row_item in enumerate(data):
for col_index, col_item in enumerate(row_item):
# 如果有表头 第二种数据格式就要价格判断单独处理表头
if row_index == 0:
# 直接写入 col_item的值
sheet.cell(row=row_index + 1, column=col_index + 1, value=col_item)
else:
# 获取字典中 {'name': 'John Brown'}, {'age': 18}, {'address': 'New York No. 1 Lake Park'}
# list数组列表后为 ['John Brown',18,'New York No. 1 Lake Park']
arr2 = list(col_item.values())
# 数组转换为字符串
str2 = ','.join(str(i) for i in arr2)
# 写入
sheet.cell(row=row_index + 1, column=col_index + 1, value=str2)
# 写入excel文件 如果path路径的文件不存在那么就会自动创建
workbook.save(path)
print('写入成功')
class readTxt(object):
# readtxt
def readtxt(path, file):
print(path)
filepath = os.path.join(path, file)
print(‘filepath:’)
print(filepath)
f = open(filepath, encoding=“utf-8”)
result = f.readlines()
f.close()
return result
创建工作文件夹,如果没有就创建,没有就创建;
def mkdir(path):
# 引入模块
import os
# 去除首位空格
path = path.strip()
# 去除尾部 \ 符号
path = path.rstrip("\")
# 判断路径是否存在
# 存在 True
# 不存在 False
isExists = os.path.exists(path)
print(isExists)
# 判断结果
if not isExists:
# 如果不存在则创建目录
# 创建目录操作函数
os.makedirs(path)
print
p