包含使用python3读取json文件,写入json文件,读取csv文件,写入csv文件,读取pickle,写入pickle,还有读取指定文件夹下的所有文件,复制文件到指定路径,创建文件夹,多进程处理列表数据,这里也算做个记录这样下次用到的时候就不用再次查找了

# -*- coding: utf-8 -*-
# 存放常用的操作函数
import pickle
import csv
import codecs
import os
import multiprocessing as mp
import syscsv.field_size_limit(500 * 1024 * 1024)
import jsondef to_number(s):#判断是否是数字,返回字符串转化的数字try:if '.' in s:float(s)return float(s)else:int(s)return int(s)except ValueError:return sdef get_input_args_dict(input_args=['']):# 输入参数,获取返回的参数字典args_dict = {}count = 0for each_str in input_args:if each_str.startswith('--'):args_dict.update({each_str[2:]: to_number(input_args[count + 1])})count += 1return args_dictdef write_dict2json(dictdata, save_path="test_dict.json"):# 字典保存为json文件try:json_str = json.dumps(dictdata)if dictdata == {}:returnwith open(save_path, 'w') as f:json.dump(dictdata, f, indent=4)except Exception as e:print("write_dict2json Error")def load_jsondata(file_path='FARE_result0.225.pkl.json'):# 读取json文件with open(file_path, 'r', encoding='utf8')as fp:json_data = json.load(fp)return json_datadef get_data_path(dir="E:\\avclass\\behavior\\behavior", ftype=''):# 获取指定文件下所有文件的全路径,返回一个列表g = os.walk(dir)print("正在读取" + dir + "下的所有文件路径名")print("读取的文件后缀名:" + ftype)result_ls = []for path, d, filelist in g:for filename in filelist:if filename.endswith(ftype):final_path = os.path.join(path, filename)final_path=final_path.replace('\\','/')#统一换成/结尾result_ls.append(final_path)return result_lsdef load_picklefile(filename):# 读取pickle文件if not filename.endswith('.pkl'):filename = filename + '.pkl'pickfile = open(filename, 'rb')listfile = pickle.load(pickfile)return listfile# -*-coding:utf-8 -*-
def write_to_pickle(dictdata, filename):# 把dict_data以pickle的形式保存if not filename.endswith('.pkl'):filename = filename + '.pkl'pick_file = open(filename, 'wb')pickle.dump(dictdata, pick_file)pick_file.close()def read_csv(filename="A_test_data.csv"):# 读取csv文件full_data = []with codecs.open(filename, 'r', encoding='utf_8_sig', errors='ignore') as f:reader = csv.reader(f)for row in reader:full_data.append(row)return full_data[1:]  # 删去抬头def write_csv(answer_data=[(0, 0)], data_head=[("域名", "域名排名", "家族", "类型")
], filename='default.csv'):# 把数据写入csv文件data = data_head + answer_dataf = codecs.open(filename, 'w', 'utf_8_sig', errors='ignore')writer = csv.writer(f)for i in data:writer.writerow(i)f.close()def update_count_dict(data_dict={}, count_str='hi'):# 更新统计字典if count_str in data_dict.keys():data_dict.update({count_str: 1 + data_dict.get(count_str)})else:data_dict.update({count_str: 1})def update_list_dict(data_dict={}, input_str='hi', update_fam='new_fam'):# 更新列表字典former_list = data_dict.get(update_fam)if former_list is None:data_dict.update({update_fam: [input_str]})else:former_list.append(input_str)data_dict.update({update_fam: former_list})def makedir(path):# 判断路径是否存在isExists = os.path.exists(path)if not isExists:# 如果不存在,则创建目录(多层)os.makedirs(path)print(path + '目录创建')return Trueelse:return Falsedef mycopyfile(srcfile, dstpath):# 复制文件到指定路径if not os.path.isfile(srcfile):print("%s not exist!" % (srcfile))else:fpath, fname = os.path.split(srcfile)  # 分离文件名和路径if not os.path.exists(dstpath):os.makedirs(dstpath)  # 创建路径shutil.copy(srcfile, dstpath + fname)  # 复制文件print("copy %s -> %s" % (srcfile, dstpath + fname))def task_split(task_list=None, maxprocess_num=2):# 根据进程数对需要处理的列表进行内容切片以便分配给不同进程处理if task_list is None:task_list = []temp = []step = len(task_list) // maxprocess_numfor count in range(0, maxprocess_num - 1):temp.append(task_list[step * count:step * count + step])temp.append(task_list[step * (maxprocess_num - 1):])return tempdef load_file(file_path=""):#根据文件结尾处理文件if file_path.endswith('.pkl'):return load_picklefile(file_path)if file_path.endswith('.json'):return load_jsondata(file_path)def multiprocess_task_list(task_list, task_function, maxprocess_num, have_return, *input_args):# 多进程处理列表数据splited_task = task_split(task_list, maxprocess_num)pool = mp.Pool(processes=maxprocess_num)if have_return != True and have_return != False:print("请设置have_return参数!")returnif have_return:# 如果有返回值,那么准备一个公共的列表,在调用函数的时候将结果存入该列表中manager = mp.Managerall_result_list = manager().list()for process_id in range(maxprocess_num):# 多进程处理数据pool.apply_async(task_function, args=(splited_task[process_id], all_result_list, *input_args), )pool.close()pool.join()return all_result_listelse:for process_id in range(maxprocess_num):# 多进程处理数据pool.apply_async(task_function, args=(splited_task[process_id], *input_args), )pool.close()pool.join()

常用的python读写函数相关推荐

  1. python counter函数定义_分享几个自己常用的Python高级函数

    哈喽大家好我是蚂蚁,今天给大家分享几个我自己常用的Python相对高级点的函数,这些函数在特定的场景下能节省大量的代码. 简单列举一下我想要介绍的几个函数: counter:计数器 defaultdi ...

  2. php打开文件读写函数,php中常用文件操作读写函数介绍

    本文章介绍了下面几个常用的文件操作函数 file_get_contents 读取整个文件内容 fopen 创建和打开文件 fclose 关闭文件 fgets 读取文件一行内容 file_exists ...

  3. php文件读写用什么函数,php中常用文件操作读写函数介绍_PHP教程

    本文章介绍了下面几个常用的文件操作函数 file_get_contents 读取整个文件内容 fopen 创建和打开文件 fclose 关闭文件 fgets 读取文件一行内容 file_exists ...

  4. python 读写函数

    1.open 使用open打开文件后一定要记得调用文件对象的close()方法.比如可以用try/finally语句来确保最后能关闭文件. file_object = open('thefile.tx ...

  5. 对比python字符串函数,学习pandas的str矢量化字符串函数

    1.概述 python字符串应该是python里面最重要的数据类型了,因此学会怎么处理各种各样的字符串,显得尤为重要. 我们不仅要学会怎么处理单个字符串,这个就需要学习"python字符串函 ...

  6. 教你如何运用python实现简单文件读写函数

    这篇文章主要为大家详细介绍了python实现简单文件读写函数,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下 python作为脚本性语言,加上它的简便易用性.会经常当作脚 ...

  7. python常用函数-Python小白必备的8个最常用的内置函数(推荐)

    Python给我们内置了大量功能函数,官方文档上列出了69个,有些是我们是平时开发中经常遇到的,也有一些函数很少被用到,这里列举被开发者使用最频繁的8个函数以及他们的详细用法 print() prin ...

  8. python 常用内置函数_Python小白必备的8个最常用的内置函数(推荐)

    Python给我们内置了大量功能函数,官方文档上列出了69个,有些是我们是平时开发中经常遇到的,也有一些函数很少被用到,这里列举被开发者使用最频繁的8个函数以及他们的详细用法 print() prin ...

  9. python学习之最常用的内置函数

    python学习之最常用的内置函数 Python 内置函数总共有70余个(通常把内置类也统称为内置函数),覆盖面广,功能强大.不过,对于初学者在初级阶段,掌握下面几个函数是当务之急. (1) 控制台输 ...

最新文章

  1. 关于might_sleep的一点说明【转】
  2. python 14 装饰器
  3. VScode 格式化代码快捷键、修改快捷键
  4. 131_Power Query之获取钉钉日志自动刷新Power BI报告
  5. windows installer没有正确安装_电脑还可以这样禁止软件自动安装,后悔知道得太晚...
  6. 内核中的UDP socket流程(5)——inet_create
  7. Spring(6)---自动装配Beans
  8. 那些有关求解next数组的算法
  9. linux轮训创建文件夹,Linux文件和目录管理相关命令(三)
  10. [转载]仿射变换(Affine Transformation)
  11. Windows 10 KB3124200补丁无法安装的临时解决方案
  12. 【雷达信号处理】---模糊函数与仿真
  13. 获取代理IP的三种途径
  14. 基于ZigBee的城市照明监控系统网关节点的软硬件设计
  15. 数学文化赏析期末笔记
  16. 个人电脑windows装青龙面板,本地运行,无需服务器,本人亲测成功
  17. 数据库简单sql语句(CURD)
  18. ARM S5PV210 X210 刷机教程总结
  19. 2022第13届蓝桥杯Java省赛B组个人题解
  20. 两大图灵奖得主力作:计算机架构的新黄金时代

热门文章

  1. 你的小米手机升级MIUI11后,电池掉电很快?那是这些设置没关掉吧
  2. 《痞子衡嵌入式半月刊》 第 69 期
  3. 京东商品主图怎么保存?如何正确的保存到原图?
  4. 蛙蛙推荐:蛙蛙牌关键词提取算法
  5. Linux是什么 ?
  6. Unity 之 Ping类简析尝试使用
  7. 面向对象程序设计——埃拉托色尼筛法(C++)(已更新)
  8. Docker Hub Automated Build with GitHub
  9. 魔法少女小圆计算机音乐,求魔法少女小圆一些背景音乐的名字
  10. 【Python】利用滑动窗口计算全基因组每个窗口上CNV的拷贝数和Vst