====================================================================python
shutil模块是python为咱们封装的一个高级的高级的文件、文件夹、压缩包 处理模块,它本质上是调用open方法对文件进行读写。模块相对比较简单,记住几个经常使用的方法便可。安全
shutil.copyfileobj(fsrc, fdst[, length])
将文件内容拷贝到另外一个文件中。这个是基本方法,其余的拷贝方法都是在后台调用这个方法。 函数
import shutil测试
shutil.copyfileobj(open('old.xml','r'), open('new.xml', 'w'))线程
shutil.copyfile(src, dst)
拷贝文件 debug
shutil.copyfile('f1.log', 'f2.log')日志
shutil.copymode(src, dst)
仅拷贝权限。内容、组、用户均不变 orm
shutil.copymode('f1.log', 'f2.log')xml
四、shutil.copystat(src, dst)
仅拷贝状态的信息,包括:mode bits, atime, mtime, flags对象
shutil.copystat('f1.log', 'f2.log')
五、 shutil.copy(src, dst)
拷贝文件和权限
shutil.copy('f1.log', 'f2.log')
六、shutil.copy2(src, dst)
拷贝文件和状态信息
shutil.copy2('f1.log', 'f2.log')
七、shutil.ignore_patterns(*patterns)
shutil.copytree(src, dst, symlinks=False, ignore=None)
递归的去拷贝文件夹。ignor_patterns是指忽略不拷贝的文件
shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))
八、shutil.rmtree(path[, ignore_errors[, onerror]])
递归的去删除文件
shutil.rmtree('folder1')
九、shutil.move(src, dst)
递归的去移动文件,它相似mv命令,其实就是重命名。
shutil.move('folder1', 'folder3')
10、shutil.make_archive(base_name, format,...)
建立压缩包并返回文件路径,例如:zip、tar
建立压缩包并返回文件路径,例如:zip、tar
● base_name: 压缩包的文件名,也能够是压缩包的路径。只是文件名时,则保存至当前目录,不然保存至指定路径,
如:www =>保存至当前路径
如:/Users/wupeiqi/www =>保存至/Users/wupeiqi/
● format: 压缩包种类,“zip”, “tar”, “bztar”,“gztar”
● root_dir: 要压缩的文件夹路径(默认当前目录)
● owner: 用户,默认当前用户
● group: 组,默认当前组
● logger: 用于记录日志,一般是logging.Logger对象
#将 /Users/wupeiqi/Downloads/test 下的文件打包放置当前程序目录
import shutil
ret = shutil.make_archive("wwwwwwwwww", 'gztar', root_dir='/Users/wupeiqi/Downloads/test')
#将 /Users/wupeiqi/Downloads/test 下的文件打包放置 /Users/wupeiqi/目录
import shutil
ret = shutil.make_archive("/Users/wupeiqi/wwwwwwwwww", 'gztar', root_dir='/Users/wupeiqi/Downloads/test')
shutil 对压缩包的处理本质上是调用 ZipFile 和 TarFile 两个模块来进行的,但封装的比较简单,不是很好用,建议仍是使用ZipFile 和 TarFile 模块。
==========================================================
当你须要压缩文件的时候,使用这个模块会比较方便。
import zipfile
# 压缩
z = zipfile.ZipFile('laxi.zip', 'w')
z.write('a.log')
z.write('data.data') # 能够一个一个添加文件进压缩包
z.close()
# 解压
z = zipfile.ZipFile('laxi.zip', 'r')
z.extractall() # 这是一次性将压缩包内的文件所有解压出来
z.close()
要单独解压压缩包内的某个文件就须要先得到压缩包内的文件名列表。zipfile提供了一个namelist方法。
import zipfile
z = zipfile.ZipFile('laxi.zip', 'r')
ret = z.namelist()
print(ret)
z.close()
运行结果:
['testfile.bak', 'testfile.dat']
而后经过具体的文件名去解压某个文件。zipfile提供了extract方法。
import zipfile
z = zipfile.ZipFile('laxi.zip', 'r')
z.extract("testfile.bak")
z.close()
===============================================================
getpass模块很是简单,它可以让你在输入密码的时候不会在屏幕上显示密码,安全性更高。注意:在pycharm环境里这个模块用不了!
getpass模块只有2个经常使用方法:getpass和getuser。参考下面的例子:
import getpass
pwd = getpass.getpass("请输入密码: ") # 可代替input方法,接收用户输入的密码
print(getpass.getuser()) # getuser方法会返回当前执行程序的用户名
===================================================================
这是一个python内置的二分查找法模块,模块内只有4个方法:bisect_right、bisect_left、insort_right和insort_left。而后经过将bisect_right赋值给bisect,将insort_right赋值给insort实现向后兼容。实际使用中,是须要记住bisect和insort两个方法便可。
bisect模块的使用方法一般是:bisect.bisect(list,x),其中x表示要查找的值,list是一个默认已经排好序的列表。
bisect():返回值是x在列表中应处的位置下标,并不修改列表自己。
import bisect
x = 200
list1 = [1, 3, 6, 24, 55, 78, 454, 555, 1234, 6900]
ret = bisect.bisect(list1, x)
print("返回值: ", ret)
print("list1 = ", list1)
运行结果:
返回值: 6
list1 = [1, 3, 6, 24, 55, 78, 454, 555, 1234, 6900]
insort():返回值是None,可是会将x插入到列表中生成新的列表。x插在它的大小排序所在位置。
import bisect
x = 200
list1 = [1, 3, 6, 24, 55, 78, 454, 555, 1234, 6900]
ret = bisect.insort(list1, x)
print("返回值: ", ret)
print("list1 = ", list1)
运行结果:
返回值: None
list1 = [1, 3, 6, 24, 55, 78, 200, 454, 555, 1234, 6900]
===========================================================================
使用过python内置的open方法处理文件的同窗都知道,它没有直接修改文件内容的方法。这个fileinput能够帮助咱们轻松的实现文件内容的修改功能。fileinput模块中的重要方法以下:
input([files[, inplace[, backup]])
最重要的方法,用于遍历打开的文件,inplace为True的时候,会将修改写入文件,backup为True的时候会进行备份操做。
filename()
返回当前文件的名字
lineno()
返回当前(累计)的行数。同时处理多个文件时,行数会累计。
filelineno()
返回当前文件的总行数。处理新文件时,行数会重置为1,从新计数。
isfirstline()
检查当前行是不是文件的第一行
isstdin()
检查最后一行是否来自sys.stdin
nextfile()
关闭当前文件,移动到下一个文件(fileinput是能够同时处理多个文件的!)
close()
关闭整个文件链,结束迭代。
为了演示fileinput的使用,假设编写了以下的一个脚本,想要为其代码进行编号。为了让脚本在进行代码编号后仍然可以正常运行,咱们只能在每一行的右侧加上#来注释行号。其中,咱们假定每一个代码行最多有40个字符。具体代码以下:
import fileinput
f = fileinput.input(inplace=True)
for line in f:
line = line.rstrip()
num = fileinput.lineno()
print("%-40s # %2i" % (line, num))
f.close()
注意,只能使用rstrip,不能直接用strip,那样会把左边的缩进也给去掉了。
请在终端环境下,使用python fileinput_test.py fileinput_test.py的方式执行程序,结果以下:
import fileinput # 1
# 2
f = fileinput.input(inplace=True) # 3
for line in f: # 4
line = line.rstrip() # 5
num = fileinput.lineno() # 6
print("%-40s # %2i" % (line, num)) # 7
f.close() # 8
要当心使用inplace参数,它会修改文件。应该在不适用inplace设置的状况下仔细测试本身的程序(这样只会打印出结果),在确保程序工做正常后再修改文件。
===========================================================================
python一样提供logging日志记录模块,如下是logging模块配置参数
logging.basicConfig()函数中可经过具体参数来更改logging模块默认行为,可用参数有:
filename:用指定的文件名建立FiledHandler,这样日志会被存储在指定的文件中。
filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。
format:指定handler使用的日志显示格式。
datefmt:指定日期时间格式。
level:设置rootlogger(后边会讲解具体概念)的日志级别
stream:用指定的stream建立StreamHandler。能够指定输出到sys.stderr,sys.stdout或者文件(f=open(‘test.log’,’w’)),默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。
format参数中可能用到的格式化串:
%(name)s Logger的名字
%(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用户输出的消息
logging简单测试
import logging
logging.debug('debug message')
logging.info('info message')
logging.warning('warning message')
logging.error('error message')
logging.critical('critical message'
默认状况下Python的logging模块将日志打印到了标准输出中,且只显示了大于等于WARNING级别的日志,这说明默认的日志级别设置为WARNING(日志级别等级CRITICAL > ERROR > WARNING > INFO > DEBUG),默认的日志格式为日志级别:Logger名称:用户输出消息。
logging自定义格式输出
import logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename='test.log',
filemode='w')
logging.debug('debug message')
logging.info('info message')
logging.warning('warning message')
logging.error('error message')
logging.critical('critical message')
生成test.log文件,内容以下
logging对象配置
import logging
logger = logging.getLogger()
# 建立一个handler,用于写入日志文件
fh = logging.FileHandler('test.log',encoding='utf-8')
# 再建立一个handler,用于输出到控制台
ch = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
ch.setFormatter(formatter)
logger.addHandler(fh) #logger对象能够添加多个fh和ch对象
logger.addHandler(ch)
logger.debug('logger debug message')
logger.info('logger info message')
logger.warning('logger warning message')
logger.error('logger error message')
logger.critical('logger critical message')
logging库提供了多个组件:Logger、Handler、Filter、Formatter。Logger对象提供应用程序可直接使用的接口,Handler发送日志到适当的目的地,Filter提供了过滤日志信息的方法,Formatter指定日志显示格式。另外,能够经过:logger.setLevel(logging.Debug)设置级别,固然,也能够经过
fh.setLevel(logging.Debug)单对文件流设置某个级别。