我是靠谱客的博主 健壮薯片,这篇文章主要介绍Python常用模块整理,现在分享给大家,希望可以做个参考。

@[TOC]Python常用模块小整理

os模块

#.py脚本所在项目路径
projectpath = os.path.dirname(os.path.abspath(file))
print(projectpath )

#连接目录与文件名或目录
os.path.join(path,name):

random模块

①随机小数 :随机获取0-20之间的小数,并保留n位数

复制代码
1
2
3
4
5
6
7
8
9
#coding=utf-8 import random #生成随机数,浮点类型 a = random.uniform(0, 20) #控制随机数的精度round(数值,精度) n=3 print round(a, n)

②随机整数

复制代码
1
2
3
4
5
6
7
8
9
10
import random print(random.randint(0,20)) #随机一个大于等于0且小于等于20的整数 print(random.randrange(1,10)) #从指定范围内,按指定基数递增的集合中 获取一个随机数 n = 1 m = 6 print(random.randrange(n,20,m)) #n=奇数,就以6递增奇数,随机选取一个实数;n=偶数同理

③从序列中获取一个随机元素。其函数原型为:random.choice(sequence)。参数sequence表示一个有序类型,list, tuple, 字符串都属于sequence

复制代码
1
2
3
4
5
6
7
import random print(random.choice("Python")) #随机返回Python中任意一个字母 print(random.choice(["JaingCaiYong", "is", "a", "handsome", "boy"])) #随机返回参数列表中任意一个元素 print(random.choice(("Tuple", "List", "Dict")))

④从列表中随机获取n个元素

复制代码
1
2
3
4
5
6
7
8
import random # random.sample(sequence, k) #从指定序列中随机获取指定长度的片断。sample函数不会修改原有序列 list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] res = random.sample(list, 5) # 从list中随机获取5个元素,作为一个片断返回 print(res)

⑤打乱列表顺序

复制代码
1
2
3
4
5
import random list = [1,2,3,a,b,c] random.shuffle(list) print(list)

⑥号码生成器

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
import random def random_num(m): code = '' for i in range(m): ran1 = random.randint(0, 9) ran2 = chr(random.randint(65, 90)) #chr() 用一个范围在 range(256)内的(就是0~255)整数作参数,返回一个对应的字符 add = random.choice([ran1,ran2]) code = ''.join([code, str(add)]) return code rand = random_num(m=6) #m为要生成的几位数 print(rand)

shutil模块

ip1目录下的文件拷贝到ip2对应的目录下

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import os import re import shutil import time from datetime import date, timedelta exportfile ='\\ip1\d$\yswt' targetpath ='\\ip2\d$\GtjaFile\dysrzrq\jzjy\%s' % (date.today() + timedelta(days=-1)).strftime("%Y%m%d") #% (date.today() + timedelta(days=-1)).strftime("%Y%m%d") -1表示天数,获取前一交易日的文件,如果想找后n天的,同理days = -n if not os.path.isdir(targetpath): os.makedirs(targetpath) else: pass file_list = os.listdir(exportfile) # 获取文件夹下所有的文件 fileall = [] for file in file_list: if re.findall('.*%s.*'%time.strftime("%Y%m%d"), file): # 判断文件是否是今天日期的 fileall.append(file) srcFilename = exportfile + '\' + file # 找到指定目录下的文件 shutil.copy(srcFilename, targetpath) copyCommand = 'xcopy %s %s /s /e /c /y /h /r' % (srcFilename, targetpath) # 拷贝文件到指定目录并覆盖 if os.system(copyCommand) == 0: # 执行该copy命令 print('拷贝当天文件%s个完成' % len(fileall))

logging模块

logging函数根据它们用来跟踪的事件的级别或严重程度来命名。标准级别及其适用性描述如下(以严重程度递增排序):

级别何时使用
DEBUG详细信息,一般只在调试问题时使用
INFO证明事情按预期工作
WARNING某些没有预料到的事件的提示,或者在将来可能会出现的问题提示。例如:磁盘空间不足。但是软件还是会照常运行
ERROR由于更严重的问题,软件已不能执行一些功能了
CRITICAL严重错误,表明软件已不能继续运行了
级别数字值
CRITICAL50
ERROR40
WARNING30
INFO20
DEBUG10
NOTSET0

默认等级是WARNING,这意味着仅仅这个等级及以上的才会反馈信息,除非logging模块被用来做其它事情。

一、输出日志到控制台
其中方法setLevel可以设置日志对应的等级,按照等级打印到控制台

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import logging #第1步:创建日志器对象 #创建日志对象(记录器),默认是warning等级日志 logger = logging.getLogger() #第2步:创建控制台处理器 console_handler = logging.StreamHandler() #定义控制台的等级 console_handler.setLevel(level='DEBUG') #第1步控制器中添加控制台处理器 log.addHandler(console_handler) logging.debug("这日志是debug级别") logging.info("这日志是info级别") logging.warning("这日志是warning级别") logging.error("这日志是error级别") logging.critical("这日志是critical级别")

二、输出日志到指定文件夹

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import logging #创建日志对象(记录器) log = logging.getLogger() #创建文本处理器。filename是日志输出路径,mode文件权限a添加,encoding文件格式 file_handler = logging.FileHandler(filename='d:/log.txt',mode='a',encoding='utf-8') #定义文本的等级 file_handler.setLevel(level='ERROR') #第1步控制器中添加控制台处理器 log.addHandler(file_handler) logging.debug("这日志是debug级别") logging.info("这日志是info级别") logging.warning("这日志是warning级别") logging.error("这日志是error级别") logging.critical("这日志是critical级别")

日志封装:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import logging class log(object): def __init__(self, level="DEBUG"): # 日志处理器 self.log = logging.getLogger("日志") self.log.setLevel(level) def get_formatter(self): #格式器,定义输出的是控制台,还是文本格式 console_fmt = logging.Formatter(fmt="%(name)s--->%(levelname)s--->%(asctime)s--->%(message)s") file_fmt = logging.Formatter(fmt="%(lineno)d--->%(asctime)s---->%(levelname)s--->%(message)s") return console_fmt, file_fmt def console_handle(self, level="DEBUG"): #控制台处理器 console_handler = logging.StreamHandler() console_handler.setLevel(level) #处理器添加格式 console_handler.setFormatter(self.get_formatter()[0]) return console_handler def file_handle(self,log_path, level="DEBUG"): #文本处理器 file_handler = logging.FileHandler(filename=log_path, mode="a", encoding="utf-8") file_handler.setLevel(level) # 处理器添加格式器 file_handler.setFormatter(self.get_formatter()[1]) return file_handler def get_log(self,log_path): #log_path 日志输出的路径地址 如d:/log.txt self.log.addHandler(self.console_handle()) # 日志器添加控制台处理器 self.log.addHandler(self.file_handle(log_path)) # 日志器添加文件处理器 return self.log if __name__ == '__main__': pass

关于Formatter的讲解
Formatter对象设置日志信息最后的规则、结构和内容,默认的时间格式为%Y-%m-%d %H:%M:%S,下面是Formatter常用的一些信息

%(name)sLogger的名字
%(levelno)s数字形式的日志级别
%(levelname)s文本形式的日志级别
%(pathname)s调用日志输出函数的模块的完整路径名,可能没有
%(filename)s调用日志输出函数的模块的文件名
%(module)s
%(funcName)s调用日志输出函数的函数名
%(lineno)d调用日志输出函数的语句所在的代码行
%(created)f当前时间,用UNIX标准的表示时间的浮 点数表示
%(relativeCreated)d输出日志信息时的,自Logger创建以 来的毫秒数
%(asctime)s字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒
%(thread)d线程ID,可能没有
%(threadName)s线程名,可能没有
%(process)d进程ID,可能没有
%(message)s用户输出的消息

csv模块

此模块读取csv后缀结尾的文件,并进行相关操作

获取csv总行数

open(filename)打开csv文件
readlines读取csv文件所有行,并以列表形式返回。列表中的每一个元素就是csv文件中的一行。
len取得列表长度

复制代码
1
2
total = len(open(filename).readlines())
csv常用读写封装
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import pandas as pd import csv class CsvFile: def PdWriteCsv(self,writepath): #使用pandas写入csv a = ['第一列行1','第一列行2'] b = ['第二列行1','第二列行2'] dataframe = pd.DataFrame({'列1': a ,'列2': b}) #字典中的key值即为csv中列名 dataframe.to_csv(writepath,index=False,sep=',') #将DataFrame存储为csv,index表示是否显示行名,default=True def ListWriteCsv(self,writepath): #列表写入csv csvFile = open(writepath, 'w', newline='') # 设置newline,否则两行之间会空一行 writer = csv.writer(csvFile) writer.writerow(["a_name", "b_name"]) # 先写入columns_name列名 writer.writerows([[1, 2], [2, 3]]) # 写入多行用writerows def DictWriteCsv(self,writepath): # 从字典写入csv文件 dic = {'one': 1, 'two': 2, 'three': 3} csvFile = open(writepath, 'w', newline='') writer = csv.writer(csvFile) for key in dic: writer.writerow([key,dic[key]]) def ReadCsv(self,writepath): # 以字典读取csv文件 csvFile = open(writepath, "r") dict_reader = csv.DictReader(csvFile) for row in dict_reader: print(row,row['a_name']) if __name__ == '__main__': pass # CsvFile().ListWriteCsv(writepath=r"D:write.csv") # CsvFile().ReadCsv(writepath=r"D:write.csv")

最后

以上就是健壮薯片最近收集整理的关于Python常用模块整理的全部内容,更多相关Python常用模块整理内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(54)

评论列表共有 0 条评论

立即
投稿
返回
顶部