Python写入EXCEL
pd.ExcelWriter写入open写入方法write与writelines对比表格Dataframe形式的写入for、with 位置对比
·
pd.ExcelWriter写入
- 语法
data1=1
with pd.ExcelWriter(r"D:\lqwj_group.xlsx") as writers:
data1.to_excel(writers, sheet_name="sheet1", index=False)
writers.save()
ExcelWriter写入需要save(),但是不需要close().
- 示例(分组写入多个sheet):
分组groupby返回的值为字典形式{key:value}
也要注意一下with和for和if的嵌套位置,可能会造成只写入一个表的情况
import pandas as pd
data1 = pd.read_excel(r"D:\dsd\lqwj_raw.xlsx")
data1["bag_okno"] = data1["file_name"].str[:15]
group1 = data1.groupby(data1["bag_okno"])
with pd.ExcelWriter(r"D:\dsd\lqwj_group.xlsx") as writers:
for i, n in group1:
# print("i", i, "n", n)
if i == "hellobike_sf_ok":
n.to_excel(writers, sheet_name="sf_ok", index=False)
print("sf_ok_over")
elif i == "hellobike_sf_no":
n.to_excel(writers, sheet_name="sf_no", index=False)
print("sf_no_over")
elif i == "hellobike_dc_ok":
n.to_excel(writers, sheet_name="dc_ok", index=False)
print("dc_ok_over")
elif i == "hellobike_dc_no":
n.to_excel(writers, sheet_name="dc_no", index=False)
print("dc_no_over")
else:
print("error")
writers.save()
open写入方法
write与writelines对比
write():只能写入字符串。会把
writelines():可以写入字符串,列表,元组等。
with open(path, 'a+') as f:
print(rr)
f.write(str(rr)+'\n')
f.writelines(str(rr)+'\n')
都是字符串形式时两者无区别。结果如下:
注意:如果此时需要换行的话需要转化成字符串的形式与\n
连接。否则则会在尾部直接追加。示例如下:
表格Dataframe形式的写入
另外,如果是Dataframe或者series的数据需要写入的话,需要采用to_csv
或者to_excel
的方式。
import os
import pandas as pd
path = os.getcwd() + '/test.csv'
data = pd.read_excel(r"C:\Users\EDZ\Desktop\test2.xlsx")
print(type(data))
data.to_csv(path, index=False, encoding='GB2312')
for、with 位置对比
with open(path, 'a+') as f:
for row in rr:
print(row)
f.writelines(str(row)+'\n')
for row in rr:
with open(path, 'a+') as f:
print(row)
f.writelines(str(row)+'\n')
for row in rr:
with open(path, 'a+') as f:
print(row)
f.write(str(row)+'\n')
- 用了for循坏之后,write与writelines结果相同。
- with 和for 调换位置后并不影响循坏,即输出结果相同。
更多推荐
已为社区贡献1条内容
所有评论(0)