shutil模块中的文件、文件夹、压缩包处理模块是怎样的
发表于:2025-11-07 作者:千家信息网编辑
千家信息网最后更新 2025年11月07日,shutil模块中的文件、文件夹、压缩包处理模块是怎样的,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。shutil.copyfile
千家信息网最后更新 2025年11月07日shutil模块中的文件、文件夹、压缩包处理模块是怎样的
shutil模块中的文件、文件夹、压缩包处理模块是怎样的,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
shutil.copyfileobj(fsrc, fdst[, length])将文件内容拷贝到另一个文件中,length是每次复制的大小
guessage.py中内容"""猜年龄游戏:允许用户最多猜三次,猜了三次后,询问是都继续玩,如果输入Y,可以继续猜三次,否则退出"""age = 23count = 0while count < 3: try: guess_age = int(input("input the age of you think:")) except ValueError: print("you should input one number!") count = count + 1 continue if guess_age > 23: print("the age you input is too big!") elif guess_age < 23: print("the age you input is too small!") else: print("excellent!you are right!") break count = count + 1 while count == 3: your_choice = input("you only have three chances,would you like to continue(Y|y/N|n):") if your_choice.lower() == "y": count = 0 elif your_choice.lower() =="n": break else: print("your input is illegal!input again!")"正确的程序运行代码"#!/usr/bin/env python# -*- coding:utf-8 -*-# Author: vitaimport shutilshutil.copyfileobj(open("guessage.py","r",encoding="utf-8"),open("guessage_new.py","w",encoding="utf-8",10))E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.pyProcess finished with exit code 0"不加编码时,有报错信息"#!/usr/bin/env python# -*- coding:utf-8 -*-# Author: vitaimport shutilshutil.copyfileobj(open("guessage.py","r"),open("guessage_new.py","w"))E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.pyTraceback (most recent call last): File "E:/PythonProject/python-test/BasicGrammer/test.py", line 5, in shutil.copyfileobj(open("guessage.py","r"),open("guessage_new.py","w")) File "D:\software2\Python3\install\lib\shutil.py", line 79, in copyfileobj buf = fsrc.read(length)UnicodeDecodeError: 'gbk' codec can't decode byte 0xae in position 29: illegal multibyte sequenceProcess finished with exit code 1 guessage_new.py"""猜年龄游戏:允许用户最多猜三次,猜了三次后,询问是都继续玩,如果输入Y,可以继续猜三次,否则退出"""age = 23count = 0while count < 3: try: guess_age = int(input("input the age of you think:")) except ValueError: print("you should input one number!") count = count + 1 continue if guess_age > 23: print("the age you input is too big!") elif guess_age < 23: print("the age you input is too small!") else: print("excellent!you are right!") break count = count + 1 while count == 3: your_choice = input("you only have three chances,would you like to continue(Y|y/N|n):") if your_choice.lower() == "y": count = 0 elif your_choice.lower() =="n": break else: print("your input is illegal!input again!")shutil.copyfile(src, dst)拷贝文件
#!/usr/bin/env python# -*- coding:utf-8 -*-# Author: vitaimport shutilshutil.copyfile("guessage.py","guessage_new.py")#目标文件无需存在print("guessage.py",os.stat("guessage.py"))print("guessage_new.py",os.stat("guessage_new.py"))E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.pyguessage.py os.stat_result(st_mode=33206, st_ino=9007199254741804, st_dev=3466358229, st_nlink=1, st_uid=0, st_gid=0, st_size=941, st_atime=1555571381, st_mtime=1555571381, st_ctime=1555571381)guessage_new.py os.stat_result(st_mode=33206, st_ino=7881299347900196, st_dev=3466358229, st_nlink=1, st_uid=0, st_gid=0, st_size=941, st_atime=1557104769, st_mtime=1557104769, st_ctime=1557104769)Process finished with exit code 0shutil.copymode(src, dst)仅拷贝权限。内容、组、用户均不变
"程序代码"#!/usr/bin/env python# -*- coding:utf-8 -*-# Author: vitaimport shutilshutil.copymode("guessage.py","guessage_new.py")#目标文件必须存在#目标文件不存在时E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.pyTraceback (most recent call last): File "E:/PythonProject/python-test/BasicGrammer/test.py", line 5, in shutil.copymode("guessage.py","guessage_new.py") File "D:\software2\Python3\install\lib\shutil.py", line 144, in copymode chmod_func(dst, stat.S_IMODE(st.st_mode))FileNotFoundError: [WinError 2] 系统找不到指定的文件。: 'guessage_new.py'Process finished with exit code 1#新建一个文件guessage_new.py,内容为空,再运行程序#!/usr/bin/env python# -*- coding:utf-8 -*-# Author: vitaimport shutilimport osshutil.copymode("guessage.py","guessage_new.py")print("guessage.py",os.stat("guessage.py"))print("guessage_new.py",os.stat("guessage_new.py"))E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.pyguessage.py os.stat_result(st_mode=33206, st_ino=9007199254741804, st_dev=3466358229, st_nlink=1, st_uid=0, st_gid=0, st_size=941, st_atime=1555571381, st_mtime=1555571381, st_ctime=1555571381)guessage_new.py os.stat_result(st_mode=33206, st_ino=2533274790397796, st_dev=3466358229, st_nlink=1, st_uid=0, st_gid=0, st_size=61, st_atime=1557104202, st_mtime=1557104202, st_ctime=1557104202)Process finished with exit code 0 shutil.copystat(src, dst)仅拷贝状态的信息,包括:mode bits, atime, mtime, flags
#!/usr/bin/env python# -*- coding:utf-8 -*-# Author: vitaimport shutilimport osshutil.copystat("guessage.py","guessage_new.py") #目标文件必须存在print("guessage.py",os.stat("guessage.py"))print("guessage_new.py",os.stat("guessage_new.py"))E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.pyguessage.py os.stat_result(st_mode=33206, st_ino=9007199254741804, st_dev=3466358229, st_nlink=1, st_uid=0, st_gid=0, st_size=941, st_atime=1555571381, st_mtime=1555571381, st_ctime=1555571381)guessage_new.py os.stat_result(st_mode=33206, st_ino=2814749767108452, st_dev=3466358229, st_nlink=1, st_uid=0, st_gid=0, st_size=61, st_atime=1555571381, st_mtime=1555571381, st_ctime=1557104576)Process finished with exit code 0shutil.copy(src, dst)拷贝文件和权限
#!/usr/bin/env python# -*- coding:utf-8 -*-# Author: vitaimport shutilimport osshutil.copy("guessage.py","guessage_new.py")#目标文件可以不存在print("guessage.py",os.stat("guessage.py"))print("guessage_new.py",os.stat("guessage_new.py"))E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.pyguessage.py os.stat_result(st_mode=33206, st_ino=9007199254741804, st_dev=3466358229, st_nlink=1, st_uid=0, st_gid=0, st_size=941, st_atime=1555571381, st_mtime=1555571381, st_ctime=1555571381)guessage_new.py os.stat_result(st_mode=33206, st_ino=6473924464346978, st_dev=3466358229, st_nlink=1, st_uid=0, st_gid=0, st_size=941, st_atime=1557104716, st_mtime=1557104716, st_ctime=1557104716)Process finished with exit code 0shutil.copy2(src, dst)拷贝文件和状态信息
#!/usr/bin/env python# -*- coding:utf-8 -*-# Author: vitaimport shutilimport osshutil.copy2("guessage.py","guessage_new.py")print("guessage.py",os.stat("guessage.py"))print("guessage_new.py",os.stat("guessage_new.py"))E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.pyguessage.py os.stat_result(st_mode=33206, st_ino=9007199254741804, st_dev=3466358229, st_nlink=1, st_uid=0, st_gid=0, st_size=941, st_atime=1555571381, st_mtime=1555571381, st_ctime=1555571381)guessage_new.py os.stat_result(st_mode=33206, st_ino=7318349394478946, st_dev=3466358229, st_nlink=1, st_uid=0, st_gid=0, st_size=941, st_atime=1555571381, st_mtime=1555571381, st_ctime=1557104918)Process finished with exit code 0shutil.ignore_patterns(*patterns)
shutil.copytree(src, dst, symlinks=False, ignore=None)递归的去拷贝文件夹
#!/usr/bin/env python# -*- coding:utf-8 -*-# Author: vitaimport shutilimport os# 目标目录不能存在,注意对folder2目录父级目录要有可写权限,ignore的意思是排除shutil.copytree('ee', 'new_ee', ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))print(os.listdir("ee"))print(os.listdir("new_ee"))E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py['eee']['eee']Process finished with exit code 0shutil.rmtree(path[, ignore_errors[, onerror]])递归的去删除文件
#!/usr/bin/env python# -*- coding:utf-8 -*-# Author: vitaimport shutilimport osshutil.rmtree('new_ee')print(os.listdir("ee"))print(os.listdir("new_ee"))E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.pyTraceback (most recent call last):['eee'] File "E:/PythonProject/python-test/BasicGrammer/test.py", line 10, in print(os.listdir("new_ee"))FileNotFoundError: [WinError 3] 系统找不到指定的路径。: 'new_ee'Process finished with exit code 1 shutil.move(src, dst)递归的去移动文件,它类似mv命令,其实就是重命名。
#!/usr/bin/env python# -*- coding:utf-8 -*-# Author: vitaimport shutilimport osshutil.move('ee','new_ee')print(os.listdir("ee"))#move之后,源文件就不存在了print(os.listdir("new_ee"))E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.pyTraceback (most recent call last): File "E:/PythonProject/python-test/BasicGrammer/test.py", line 9, in print(os.listdir("ee"))FileNotFoundError: [WinError 3] 系统找不到指定的路径。: 'ee'Process finished with exit code 1#!/usr/bin/env python# -*- coding:utf-8 -*-# Author: vitaimport shutilimport osshutil.move('new_ee','mkdir') #可以移到另一个文件夹中print(os.listdir("mkdir"))E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py['new_ee']Process finished with exit code 0 shutil.make_archive(base_name, format,...)创建压缩包并返回文件路径,例如:zip、tar
base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,如 data_bak =>保存至当前路径如:/tmp/data_bak =>保存至/tmp/format: 压缩包种类,"zip", "tar", "bztar","gztar"root_dir: 要压缩的文件夹路径(默认当前目录)owner: 用户,默认当前用户group: 组,默认当前组logger: 用于记录日志,通常是logging.Logger对象#!/usr/bin/env python# -*- coding:utf-8 -*-# Author: vitaimport shutil#将 test2 下的文件打包放置当前程序目录import shutilimport osret = shutil.make_archive("test2_bak", 'gztar', root_dir='test2')#目标的压缩包可以是已经存在的print(os.listdir())#将 test2下的文件打包放置 mkdir目录import shutilret = shutil.make_archive("mkdir/test2_bak", 'gztar', root_dir='test2')print(os.listdir("mkdir"))E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py['.idea', 'guessage.py', 'guessage_new.py', 'mkdir', 'requirements.txt', 'test.py', 'test2', 'test2_bak.tar.gz', '__pycache__', '写文件.txt', '写文件.txt.tmp', '格式化.py', '猜年龄的游戏.jpg', '读文件.txt']['new_ee', 'test2_bak.tar.gz']Process finished with exit code 0shutil 对压缩包的处理是调用 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(path='.')z.close()tarfile压缩&解压缩import tarfile# 压缩,egon.tar这个压缩包可以是不存在的,并且可对文件夹递归放到压缩包中>>> t=tarfile.open('/tmp/egon.tar','w')>>> t.add('/test1/a.py',arcname='a.bak')>>> t.add('/test1/b.py',arcname='b.bak')>>> t.close()# 解压>>> t=tarfile.open('/tmp/egon.tar','r')>>> t.extractall('/egon')>>> t.close()关于shutil模块中的文件、文件夹、压缩包处理模块是怎样的问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注行业资讯频道了解更多相关知识。
文件
utf-8
拷贝
目录
目标
路径
文件夹
模块
内容
用户
程序
递归
处理
信息
年龄
权限
系统
问题
代码
文件名
数据库的安全要保护哪些东西
数据库安全各自的含义是什么
生产安全数据库录入
数据库的安全性及管理
数据库安全策略包含哪些
海淀数据库安全审计系统
建立农村房屋安全信息数据库
易用的数据库客户端支持安全管理
连接数据库失败ssl安全错误
数据库的锁怎样保障安全
脉动测速软件开发
网页端云服务器在哪
sql管理服务器
甘肃惠普服务器虚拟化系统云主机
软件开发的主要工作模型
青少年科技创新大赛软件开发
数据库连接无法启动
江阴戴尔服务器维修服务点
软件开发报价表.doc
敏捷软件开发的优缺点
2017陕西网络安全
石家庄java软件开发
mc服务器搭建程序
广东手机软件开发电话
网络安全意识提升
网易软件开发工资
网络服务器租用
es数据库最多只支持查多少条
杭州网络安全
极客网络安全技能挑战
排查网络安全风险重点工作通知
央行需要网络安全程序员吗
网络安全监控指标包括哪些
软件开发用不用高数
数据库trim
计算机网络技术中专
软件开发在中专属于哪个专业
计算机三级网络技术易打错
浙江小伙自学网络技术
成都爱购多网络技术有限公司