回到顶部

阅读目录

python3 pandas 读取 Excel、CSV

#!/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()

 

^_^
请喝咖啡 ×

文章部分资料可能来源于网络,如有侵权请告知删除。谢谢!

前一篇: Fiddler 更换 User-Agent
下一篇: 个人网站前端模板收集(网站模板)