本文共 18213 字,大约阅读时间需要 60 分钟。
shutil模块用于执行高级的文件操作,如复制,移动重命名等。
>>> shutil.
shutil.Error shutil._samefile
shutil.__all__ shutil.abspath
shutil.__class__ shutil.copy
shutil.__delattr__ shutil.copy2
shutil.__dict__ shutil.copyfile
shutil.__doc__ shutil.copyfileobj
shutil.__file__ shutil.copymode
shutil.__getattribute__ shutil.copystat
shutil.__hash__ shutil.copytree
shutil.__init__ shutil.destinsrc
shutil.__name__ shutil.exceptions
shutil.__new__ shutil.move
shutil.__reduce__ shutil.os
shutil.__reduce_ex__ shutil.rmtree
shutil.__repr__ shutil.stat
shutil.__setattr__ shutil.sys
shutil.__str__
copy(src, dst):复制文件
>>> shutil.copy('/root/zhu.txt','/root/tao.txt')
>>> shutil.copy('/root/zhu.txt','/root/zhuzhu')
copy(src, dst) :#对文件进行复制,src必须是文件,而dst可以是目录。
copy2(src, dst):连同权限一起复制,相当于cp -p src dst
>>> shutil.copy2('/root/zhu.txt','/root/zhuzhu')
copyfile(src, dst):dst只能是文件,
>>> shutil.copyfile('/root/zhu.txt','/root/zhuzhu')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/usr/lib/python2.4/shutil.py", line 48, in copyfile
fdst = open(dst, 'wb')
IOError: [Errno 21] Is a directory: '/root/zhuzhu'
move(src, dst) :移动
>>> shutil.move('/root/zhu.txt','/root/zhuzhu')
>>> help(shutil.move)
>>> help(shutil.move)
>>> shutil.move('/root/1.txt','/root/zhuzhu/gg.txt')
rmtree(path):删除整个目录
>>> shutil.rmtree('/root/zhuzhu')
shutil.copyfileobj(fsrc, fdst[, length]) 将文件内容拷贝到另一个文件中
>>> import shutil
# 循环读取old.txt文件内容并写入到new.txt文件当中
>>> shutil.copyfileobj(open('old.txt','r'), open('new.txt', 'w'))
>>> import os
# 查看复制过去的文件内容
>>> os.system("cat old.txt new.txt")
old
old
0
shutil.copyfile(src, dst, *, follow_symlinks=True) 拷贝整个文件,没有第二个文件就创建,有就覆盖
>>> os.system("cat old.txt new.txt")
old
new
0
>>> shutil.copyfile('old.txt', 'new.txt') # 把第二个文件内容给覆盖了
>>> os.system("cat old.txt new.txt")
old
old
0
shutil.copymode(src, dst, *, follow_symlinks=True) 仅拷贝文件权限,文件的内容、组、用户均不变
>>> os.system("ls -l old.txt new.txt")
-rw-rw-rw- 1 ansheng ansheng 4 5月 26 15:54 new.txt
-rw-rw-r-- 1 ansheng ansheng 4 5月 26 15:52 old.txt
0
>>> shutil.copymode('old.txt', 'new.txt')
# 文件权限都变成644了
>>> os.system("ls -l old.txt new.txt")
-rw-rw-r-- 1 ansheng ansheng 4 5月 26 15:54 new.txt
-rw-rw-r-- 1 ansheng ansheng 4 5月 26 15:52 old.txt
0
shutil.copystat(src, dst, *, follow_symlinks=True) 拷贝文件状态的信息,文件必须存在,不copy改动时间
>>> os.system("stat old.txt new.txt")
文件:'old.txt'
大小:4 块:8 IO 块:4096 普通文件
设备:801h/2049d Inode:1835014 硬链接:1
权限:(0664/-rw-rw-r--) Uid:( 1000/ ansheng) Gid:( 1000/ ansheng)
最近访问:2016-05-26 15:53:09.813612241 +0800
最近更改:2016-05-26 15:52:54.830640166 +0800
最近改动:2016-05-26 15:52:54.830640166 +0800
创建时间:-
文件:'new.txt'
大小:4 块:8 IO 块:4096 普通文件
设备:801h/2049d Inode:1835024 硬链接:1
权限:(0664/-rw-rw-r--) Uid:( 1000/ ansheng) Gid:( 1000/ ansheng)
最近访问:2016-05-26 15:56:22.540041783 +0800
最近更改:2016-05-26 15:54:24.244922722 +0800
最近改动:2016-05-26 15:55:38.353967649 +0800
创建时间:-
0
>>> shutil.copystat('old.txt', 'new.txt')
>>> os.system("stat old.txt new.txt")
文件:'old.txt'
大小:4 块:8 IO 块:4096 普通文件
设备:801h/2049d Inode:1835014 硬链接:1
权限:(0664/-rw-rw-r--) Uid:( 1000/ ansheng) Gid:( 1000/ ansheng)
最近访问:2016-05-26 15:53:09.813612241 +0800
最近更改:2016-05-26 15:52:54.830640166 +0800
最近改动:2016-05-26 15:52:54.830640166 +0800
创建时间:-
文件:'new.txt'
大小:4 块:8 IO 块:4096 普通文件
设备:801h/2049d Inode:1835024 硬链接:1
权限:(0664/-rw-rw-r--) Uid:( 1000/ ansheng) Gid:( 1000/ ansheng)
最近访问:2016-05-26 15:53:09.813612000 +0800
最近更改:2016-05-26 15:52:54.830640000 +0800
最近改动:2016-05-26 15:56:48.765143115 +0800
创建时间:-
0
shutil.copy(src, dst, *, follow_symlinks=True) 拷贝文件和状态信息,同样不copy改动时间
>>> os.system("stat old.txt new.txt")
文件:'old.txt'
大小:4 块:8 IO 块:4096 普通文件
设备:801h/2049d Inode:1835014 硬链接:1
权限:(0664/-rw-rw-r--) Uid:( 1000/ ansheng) Gid:( 1000/ ansheng)
最近访问:2016-05-26 15:53:09.813612241 +0800
最近更改:2016-05-26 15:52:54.830640166 +0800
最近改动:2016-05-26 15:52:54.830640166 +0800
创建时间:-
文件:'new.txt'
大小:0 块:0 IO 块:4096 普通空文件
设备:801h/2049d Inode:1835023 硬链接:1
权限:(0664/-rw-rw-r--) Uid:( 1000/ ansheng) Gid:( 1000/ ansheng)
最近访问:2016-05-26 15:57:53.448632439 +0800
最近更改:2016-05-26 15:57:53.448632439 +0800
最近改动:2016-05-26 15:57:53.448632439 +0800
创建时间:-
0
>>> shutil.copy2('old.txt', 'new.txt')
>>> os.system("stat old.txt new.txt")
文件:'old.txt'
大小:4 块:8 IO 块:4096 普通文件
设备:801h/2049d Inode:1835014 硬链接:1
权限:(0664/-rw-rw-r--) Uid:( 1000/ ansheng) Gid:( 1000/ ansheng)
最近访问:2016-05-26 15:53:09.813612241 +0800
最近更改:2016-05-26 15:52:54.830640166 +0800
最近改动:2016-05-26 15:52:54.830640166 +0800
创建时间:-
文件:'new.txt'
大小:4 块:8 IO 块:4096 普通文件
设备:801h/2049d Inode:1835023 硬链接:1
权限:(0664/-rw-rw-r--) Uid:( 1000/ ansheng) Gid:( 1000/ ansheng)
最近访问:2016-05-26 15:53:09.813612000 +0800
最近更改:2016-05-26 15:52:54.830640000 +0800
最近改动:2016-05-26 15:58:07.938760974 +0800
创建时间:-
0
shutil.ignore_patterns(*patterns)
This factory function creates a function that can be used as a callable for copytree()‘s ignore argument, ignoring files and directories that match one of the glob-style patterns provided. See the example below.
shutil.copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2, ignore_dangling_symlinks=False)
递归的去拷贝文件夹
>> os.system("tree folder1")
folder1
├── dir
├── file.txt
├── sc.pyc
├── tmp
└── vgauthsvclog.txt.0 -> /tmp/vgauthsvclog.txt.0
2 directories, 3 files
0
# folder2目录必须不存在,symlinks=True只copy链接文件,如果等于False就copy源文件,ignore等于不copy的文件或者目录
>>> shutil.copytree('folder1', 'folder2', symlinks=False, ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))
>>> os.system("tree folder2")
folder2
├── dir
├── file.txt
└── vgauthsvclog.txt.0
1 directory, 2 files
0
shutil.rmtree(path, ignore_errors=False, οnerrοr=None) 递归的去删除文件
>>> os.system("ls -d folder2")
folder2
0
>>> shutil.rmtree('folder2')
>>> os.system("ls -d folder2")
ls: 无法访问'folder2': 没有那个文件或目录
512
shutil.move(src, dst, copy_function=copy2) 递归的去移动文件,它类似mv命令,其实就是重命名。
>>> os.system("ls -ld folder1")
drwxrwxr-x 4 ansheng ansheng 4096 5月 26 16:09 folder1
0
>>> shutil.move('folder1', 'folder3')
>>> os.system("ls -ld folder1")
ls: 无法访问'folder1': 没有那个文件或目录
512
>>> os.system("ls -ld folder3")
drwxrwxr-x 4 ansheng ansheng 4096 5月 26 16:09 folder3
0
shutil.make_archive(base_name, format[, root_dir[, base_dir[, verbose[, dry_run[, owner[, group[, logger]]]]]]])
Create an archive file (such as zip or tar) and return its name.
>>> os.system("ls -dl folder3")
drwxrwxr-x 4 ansheng ansheng 4096 5月 26 16:21 folder3
0
# /home/ansheng/folder3是保存的文件,gztar是后缀名,/home/ansheng/folder3是要打包的路径
>>> shutil.make_archive("/home/ansheng/folder3", 'gztar', root_dir='/home/ansheng/folder3')
# 返回文件打包放在那儿了
'/home/ansheng/folder3.tar.gz'
>>> os.system("ls -dl /home/ansheng/folder3.tar.gz")
-rw-rw-r-- 1 ansheng ansheng 263 5月 26 16:22 /home/ansheng/folder3.tar.gz
0
可选参数如下:
参数 说明
base_name 压缩包的文件名,也可以是压缩包的路径。
format 压缩包种类,“zip”, “tar”, “bztar”,“gztar”
root_dir 要压缩的文件夹路径(默认当前目录)
owner 用户,默认当前用户
group 组,默认当前组
shutil对压缩包的处理是调用ZipFile和TarFile两个模块来进行的,后面会介绍这两个模块的使用方法。
得到当前工作目录路径:os.getcwd()
获取指定目录下的所有文件和目录名:os.listdir(dir)
删除文件:os.remove(file)
删除多个目录:os.removedirs(r"/home")
检测路径是否为文件:os.path.isfile(path)
检测路径是否为目录:os.path.isdir(path)
判断是否为绝对路径:os.path.isabs(path)
检测路径是否存在:os.path.exists(path)
返回一个路径的目录名和文件名:os.path.split(path)
分离扩展名:os.path.splitext(file)
获取路径名:os.path.dirname(file)
获取文件名:os.path.basename(file)
运行shell命令:os.system(command)
读取和设置环境变量:os.getenv()与os.putenv()
给出当前平台的行终止符:os.linesep (windows为\r\n linux为\n Mac为\r)
指示你正在使用的平台:os.name(windows为nt,linux为posix)
重命名:os.rename(old,new)
创建多级目录:os.makedirs(r"c:\python\test")
创建单个目录:os.mkdir("test")
获取文件属性:os.stat(file)
修改文件权限与时间戳:os.chmod(file)
终止当前进程:os.exit()
获取文件大小:os.path.getsize(filename)
文件操作:
文件内容替换
for line in fileinput.input("filepath",inplace=1):
line = line.replace("oldtext","newtext")
print line
os.mknod("text.txt")创建空文件
fp = open("text.txt",'w') 直接打开一个文件,如果不存在则创建文件
关于open模式:
w 以写的方式打开(如果文件存在会清空文件内容)
a 以追加的模式打开(从EOF开始,必要时创建新文件)
r+ 以读写模式打开
w+ 以读写模式打开(参见w)
a+ 以读写模式打开(参见a)
rb 以二进制模式打开
wb 以二进制模式打开(参见w)
ab 以二进制追加模式打开(参见a)
rb+ 以二进制读写模式打开(参见r+)
wb+ 以二进制读写模式打开(参见w+)
ab+ 以二进制读写模式打开(参见a+)
fp.read([size]) #size读取长度,以byte为单位
fp.readline([size]) #读一行,如果定义了size有可能返回的只是一行的一部分
fp.readlines([size]) #把文件每一行作为一个list的一个成员,并返回这个list其实它的内容是通过循环调用readline()实现的,如果提供size参数,size表示读取内容的总长,也就是说可能只读到文件的一部分
fp.write(str) #把str写到文件中,write()并不会在str后加上一个换行符
fp.writelines(seq) #把seq的内容全部写到文件中(多行一次性写入),不会加任何东西
fp.close() #关闭文件。python会在一个文件不用后自动关闭,不过这一功能没有保证
fp.flush() #把缓冲区的内容写入磁盘
fp.fileno() #返回一个长整形的文件标签
fp.isatty() #文件是否是一个终端设备文件
fp.tell() #返回文件操作标记的当前位置,以文件的开头为原点
fp.next() #返回下一行,并将文件操作标记位移到下一行
fp.seek(offset[,whence]) #将文件操作标记位移到offset的位置,这个offset一般是相对于文件的开头来计算的,一般为正数,但如果提供了whence参数就不一定了,whence可以为0表示从头开始计算,1表示以当前位置为原点计算,2表示以文件末尾为原点计算。需要注意,如果文件以a或者a+模式打开,每次进行写操作时,文件操作标记会自动返回到文件末尾
fp.truncate([size]) #把文件裁成规定大小,默认的是裁到当前文操作标记的位置
目录操作:
os.mkdir("file") #创建目录
shutil.copyfile("oldfile","newfile") #oldfile和newfile只能是文件
shutil.copy("oldfile","newfile")#oldfile只能是文件夹,newfile可以是文件或者目标目录
shutil.copytree("olddir","newdir") #复制文件夹,newdir必须不存在
os.rename("oldname","newname") #重命名文件或目录
shutil.move("oldpos","newpos") #移动文件或目录
os.remove("file") #删除文件
os.rmdir("dir") #只能删除空目录
shutil.retree("dir") #有内容或空目录都可以删
os.chdir("path") #换路径
shutil.copyfileobj(fsrc, fdst[, length]) 将文件内容拷贝到另一个文件中
import shutil
shutil.copyfileobj(open('old.xml','r'), open('new.xml', 'w'))
shutil.copyfile(src, dst)
拷贝文件
shutil.copyfile('f1.log', 'f2.log')
shutil.copymode(src, dst) 仅拷贝权限。内容、组、用户均不变
shutil.copymode('f1.log', 'f2.log')
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) 递归的去拷贝文件夹
shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))
shutil.copytree('f1', 'f2', symlinks=True, ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))
shutil.rmtree(path[, ignore_errors[, onerror]]) 递归的去删除文件
shutil.rmtree('folder1')
shutil.move(src, dst) 递归的去移动文件,它类似mv命令,其实就是重命名。
shutil.move('folder1', 'folder3')
shutil.make_archive(base_name, format,...) 创建压缩包并返回文件路径,例如:zip、tar
·base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,如:www =>保存至当前路径 如:/Users/xxx/www =>保存至/Users/xxx/
·format: 压缩包种类,“zip”, “tar”, “bztar”,“gztar”
·root_dir: 要压缩的文件夹路径(默认当前目录)
·owner: 用户,默认当前用户
·group: 组,默认当前组
·logger: 用于记录日志,通常是logging.Logger对象
#将 /Users/wupeiqi/Downloads/test 下的文件打包放置当前程序目录
import shutil
ret = shutil.make_archive("wwwwww", 'gztar', root_dir='/Users/xx/Down/test')
#将 /Users/wupeiqi/Downloads/test 下的文件打包放置 /Users/xx/目录
import shutil
ret = shutil.make_archive("/Users/xx/wwwwww", 'gztar', root_dir='/Users/xx/Down/test')
shutil 对压缩包的处理是调用 ZipFile 和 TarFile 两个模块来进行的,详细:
zipfile解压缩
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()
tarfile解压缩
import tarfile
# 压缩
tar = tarfile.open('your.tar','w')
tar.add('/Users/wupeiqi/PycharmProjects/bbs2.log', arcname='bbs2.log')
tar.add('/Users/wupeiqi/PycharmProjects/cmdb.log', arcname='cmdb.log')
tar.close()
# 解压
tar = tarfile.open('your.tar','r')
tar.extractall() # 可设置解压地址
tar.close()