目录
OS操作
判断文件或目录是否存在
def mkdir_func(path):
# 当前文件夹是否存在
folder = os.path.exists(path)
if not folder:
# 递归创建文件夹
os.makedirs(path)
print("文件夹创建成功:{}".format(path))
else:
print("文件夹已经存在:{}".format(path))
迭代创建整个目录树
def generate_file_path():
"""
生成输出文件路径
:return:
"""
# 一个点是当前目录,两个点是上级父目录
father_dir = os.path.abspath('..')
path = os.path.join(father_dir, "output_excel")
file_path = os.path.join(path, "new_excel.xlsx")
mkdir_func(path)
return file_path
获取当前.py文件路径
print(os.path.dirname(os.path.abspath(__file__))) # 获取当前文件目录
转换Windows路径
path_str.replace('\', '\\')
pandas Excel创建、修改
创建Excel、追加sheet
- 具体可以参考pandas中的ExcelWriter函数
def generate_excel_file(file_path, sheet_name, excel_data):
"""
生成output excel文件,并新增sheet
:param file_path:
:return:
"""
if not os.path.exists(file_path):
writer = pd.ExcelWriter(file_path, mode='w', engine="openpyxl")
else:
# mode只有w a两种,if_sheet_exists参数用于规定sheet_name存在情况下,是覆盖还是跳过等操作
writer = pd.ExcelWriter(file_path, mode="a", engine="openpyxl", if_sheet_exists='replace')
# DataFrame()通过输入数据Excel_data,创建了一个新的Excel表格对象,to_excel将数据写入指定文件
pd.DataFrame(excel_data).to_excel(writer, sheet_name)
writer.save()
writer.close()
print("sheet {}写入完毕".format(sheet_name))
上面代码块可以采用with函数优化,随后有时间再优化
- 运行上面代码块出现如下报错
权限错误:[errno 13]权限被拒绝:
- 原因:我当时是由于excel文件被打开,无法进行写入操作
Pandas Excel各坐标对应位置
-
可以参考这个博客的图片excel 坐标图
-
excel_data.values不包含第一行,但是包含第一列
# g_param_array 5G 4G 3G
fifth_g_param_array = excel_data.values[:, 8][: 24]
- 想要替换excel_data中的数据要采用excel_data.iloc函数
excel_data.iloc[0, 9] = tmp_array[0, 0]
不能使用excel_data.values[0, 0],没有用,无法赋值
df.iloc[i, j]其中参数坐标
df.loc["张三", "英语成绩"]其中参数直接用表头
- 关于取值
print(vm_data_values.loc[:, config_file.VM_INPUT_VM_VCORE])
- 结果如下
0 8
1 8
2 8
3 8
4 8
5 4
6 8
7 8
8 8
9 8
10 4
11 4
Name: 虚核, dtype: int64
Pandas的表结构
- 整个表示DataFrame对象,其中一行或者一列是Series对象
- 通过调用.values属性可以获得ndarray对象
class 'pandas.core.series.Series'
print(vm_data_values.loc[:, config_file.VM_INPUT_VM_VCORE].values)
- 有表头情况下,当列索引使用str标签时,只可用loc,当列索引使用索引号时,只可用iloc
- 对于已经有数据的模板template Excel,如果替换指定位置数据,必须使用iloc。 如果使用loc[i,
“标题”],则会在DataFrame对象后面增加新的列,并不会更新对应位置的数据
nf_data_values.iloc[i, -1] = storage_res # 正确,替换指定位置的数据
# 使用loc函数插入一行
df.loc[len(df)] = [10, 11, 12] # 错误,新增了一行数据,并不是替换,而是新增