在转换高德地图城市编码的过程中,有很多城市编码开头是 0,当我转成 json 的时候,出来的结果是直接吧 数字前面的 0 去掉了,不符合预期。所以此时需要对列转类型。
import os
import time
import requests
import pandas as pd
DESKTOP = os.path.join(os.path.expanduser("~"), "Desktop") # 桌面
class FormToMany:
def __init__(self, file_path, file_save_path=DESKTOP, api_url=None):
self.file_path = file_path
self.file_save_path = file_save_path
self.api_url = api_url
def to_json(self):
"""
转变成 json 对象
:return:
"""
if self.file_path.endswith(".csv"):
# citycode,列名称
data = pd.read_csv(self.file_path, encoding='gb2312', converters={'citycode': str})
else:
# citycode,列名称
data = pd.read_excel(self.file_path, encoding='gb2312', converters={'citycode': str})
# force_ascii,是否使用 ASCII 码
data = data.to_json(orient="index", force_ascii=False)
return data
def to_json_file(self):
"""
保存到 json 文件
:return:
"""
current_date = time.strftime("%Y%m%d_%H%M%S")
if self.file_path.endswith(".csv"):
# csv
file_save_name = "csv_%s.json" % current_date
else:
# xlxs
file_save_name = "xlxs_%s.json" % current_date
try:
with open(os.path.join(self.file_save_path, file_save_name), "w") as f:
f.write(self.to_json())
print("提示:数据导出成功 %s" % os.path.join(self.file_save_path, file_save_name))
return True
except Exception as e:
print(str(e))
return False
def to_json_post(self):
"""
上传 json 对象
:return:
"""
if self.file_path.endswith(".csv"):
kind = "csv"
else:
kind = "excel"
body = {
"type": kind,
"data": self.to_json()
}
try:
req = requests.post(self.api_url, data=body, timeout=180)
except Exception as e:
print(str(e))
return False
else:
if req.status_code == 200:
print("数据上传成功")
return True
else:
print("数据上传结束")
return False
if __name__ == "__main__":
pass