• Python文件存读取


    Python文件存读取

    想整理一下存读取函数,方便以后直接调用。

    读取

    1、读xls、csv、xlsx到dataframe

    这段代码非常好用,这个函数直接把各种格式文件给汇总了

    def readDataFile(readPath):  # readPath: 数据文件的地址和文件名
        try:
            if (readPath[-4:] == ".csv"):
                dfFile = pd.read_csv(readPath, header=0, sep=",")  # 间隔符为逗号,首行为标题行
                # dfFile = pd.read_csv(filePath, header=None, sep=",")  # sep: 间隔符,无标题行
            elif (readPath[-4:] == ".xls") or (readPath[-5:] == ".xlsx"):  # sheet_name 默认为 0
                dfFile = pd.read_excel(readPath,header=0)  # 首行为标题行
                # dfFile = pd.read_excel(filePath, header=None)  # 无标题行
            elif (readPath[-4:] == ".dat"):  # sep: 间隔符,header:首行是否为标题行
                dfFile = pd.read_table(readPath, sep=" ", header=0)  # 间隔符为空格,首行为标题行
                # dfFile = pd.read_table(filePath,sep=",",header=None) # 间隔符为逗号,无标题行
            else:
                print("不支持的文件格式。")
        except Exception as e:
            print("读取数据文件失败:{}".format(str(e)))
            return
        return dfFile
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    存入

    特定位置写入

    先建立一个列表,然后在列表中存入数据。写入的时候逐行写入列表中对应元素。

    import openpyxl as op
    list=[]
    tableAll = op.load_workbook(filePath)
    table1 = tableAll['lut']
    for i in range(len(list)):
        table1.cell(i+2, 11, list[i])
    tableAll.save(filePath)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    实例可以参考该文章-操作EXCEL计算3万条数据的NDVI并填入

    字典逐行存入csv

        kind_num_dict={1:0,2:0,3:0,4:2}
        mid = pd.DataFrame(list(kind_num_dict.items()))
        mid.to_csv('./p1_不同单品累加求和.csv', header=False, index=False)
    
    • 1
    • 2
    • 3

    列表中的字典元素逐行存入xlsx

    xlsx_list=[{'日期':'2020-07-01','值':35},{'日期':'2020-07-02','值':31},{'日期':'2020-07-03','值':54}]
    import pandas as pd
    
    #定义一个字典
    
    
    #将字典格式化为DataFrame数据
    
    data = pd.DataFrame(xlsx_list)
    
    #将数据写入Excel中
    
    data.to_excel('test.xlsx')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
  • 相关阅读:
    为什么 JavaScript 中的 0.1 + 0.2 不等于 0.3
    Android平台实现lottie动画
    Standalone---基础认知
    数据库MySQL中Show指令祥解
    vue ref和$refs获取dom元素
    PCB板的元素组成
    动态规划之背包问题
    编程随笔-Java | 04.栈Stack、队列Queue和双端队列Deque
    ib课程三大核心课程详细介绍
    秋招攻略秘籍,吃透25个技术栈Offer拿到手软
  • 原文地址:https://blog.csdn.net/qq_43920838/article/details/132908150