zoukankan      html  css  js  c++  java
  • 文件的存储

    1 format()

    形如str.format(),format中的内容用于代替str中的  {} 和 

    当读取的文件较大需要分开存储时可用此函数对其编号

    1 >>>"{} {}".format("hello", "world")    # 不设置指定位置,按默认顺序
    2 'hello world'
    3  
    4 >>> "{0} {1}".format("hello", "world")  # 设置指定位置
    5 'hello world'
    6  
    7 >>> "{1} {0} {1}".format("hello", "world")  # 设置指定位置
    8 'world hello world'

    参考:https://blog.csdn.net/zhchs2012/article/details/84328742

    2 存储文件时默认存储在当前程序所在的目录下,也可用 .//newfilewalk 表示存储在当前目录的newfilewalk下

    若没有newfilewalk文件夹会报错,要提前新建

    data_xls.to_csv('.\chengji\化学.csv', encoding='utf-8')

    3 若在一个程序中后面要读前面存储下的文件,此时前面用to_csv()存储时要加上index=False,此时便不会存储索引列,否则在程序后面容易出现列数不对应的错误

    4 to_csv()函数

    参数: mode: 默认是'w',即写数据,当想要将数据追加写入文件后面时用mode='a+',这个时候一定要注意header=None,否则会将列名也写入文件中,后续处理很容易出错,出错了只能用二分法找了.

    app_actived_train = pd.read_csv('./labelencoder_file/app_actived_train.csv', iterator=True)
    
    pieceID = 1
    loop = True
    while loop:
        try:
            df = app_actived_train.get_chunk(100000)  # 10万
            df.columns = ['index', 'uid', 'appid']
            df1 = df['uid']
            df1 = pd.DataFrame(df1)
            df = df['appid'].str.split('#', expand=True).stack().reset_index(level=1, drop=True).rename('appid')
            df = {'index': df.index, 'appid': df.values}
            df = pd.DataFrame(df)
            df = pd.merge(df1, df, left_index=True, right_on='index', how='left')
            df.to_csv('./labelencoder_file/app_actived_train.csv', mode='a+', index=False, header=None)
            print(pieceID * 100000)
            pieceID += 1
            del df, df1
        except StopIteration:
            loop = False
            print('imps_log process finish!')

    5 hdf5格式的存储

    如下写入和读取的时候必须要写后面的参数key,它是用于给数据分组的组名,当要往h5格式的数据中写数据式时,每次的key不能相同.

    官网链接:http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_hdf.html

    df.to_hdf('a.h5','df')
    pd.read_hdf('a.h5','df')

    6 txt文件的创建和存储

    # 创建一个txt文件,文件名为mytxtfile,并向文件写入msg
    def text_create(name, msg):
        desktop_path = "C:\Users\Administrator\Desktop\"  # 新创建的txt文件的存放路径
        full_path = desktop_path + name + '.txt'  # 也可以创建一个.doc的word文档
        file = open(full_path, 'w')
        file.write(msg)   #msg也就是下面的Hello world!
        # file.close()
     
    text_create('mytxtfile', 'Hello world!')
    # 调用函数创建一个名为mytxtfile的.txt文件,并向其写入Hello world!
    View Code
  • 相关阅读:
    python操作mysql
    django 模型
    sox应用实例:平分一个音频文件
    Python list的各种删除元素操作
    Python sort() 和 sorted() 的区别
    Linux去除文件名中的空格
    合并多个MP4文件
    把wav文件等时长切割
    删除文件里的重复行
    Shell 截取字符串
  • 原文地址:https://www.cnblogs.com/xxswkl/p/10993325.html
Copyright © 2011-2022 走看看