前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python3 pandas 读取 Excel、CSV

python3 pandas 读取 Excel、CSV

作者头像
卓越笔记
发布2023-02-18 10:18:37
7630
发布2023-02-18 10:18:37
举报
文章被收录于专栏:卓越笔记
代码语言:javascript
复制
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
@author: yinzhuoqun
@site: http://zhuoqun.info/
@email: yin@zhuoqun.info
@time: 2019/4/22 15:22
"""
import os
import time
import requests
import pandas as pd


# pip install pandas


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"):
            data = pd.read_csv(self.file_path, encoding='gb2312')
        else:
            data = pd.read_excel(self.file_path)
        data = data.to_json(orient="index")
        return data

    def to_json_file(self):
        """
        保存到 json 文件
        :return:
        """
        current_date = time.strftime("%Y%m")
        if self.file_path.endswith(".csv"):
            # 违规
            file_save_name = "order_illegal_%s.json" % current_date
        else:
            # 维权
            file_save_name = "order_rights_%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("提示:数据导出成功")
            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__":
    file_path = r"C:\Users\Desktop\orders.csv"
    # file_path = r"C:\Users\Desktop\RefundDetailReport-2019-06-25.xls"
    data = FormToMany(file_path=file_path)
    data.to_json_file()
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-8-27 2,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档