前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >matinal:python 复制、移动、删除文件及文件夹

matinal:python 复制、移动、删除文件及文件夹

作者头像
matinal
发布2023-10-13 19:32:51
2920
发布2023-10-13 19:32:51
举报
文章被收录于专栏:SAP Technical

对于文件和文件夹,我们最常做的操作分为三种:复制、移动、删除。

这三种操作可以通过shutil和os模块中的函数实现,下面通过对hello.txt的操作为例进行说明:

代码语言:javascript
复制
*复制:shutil.copy(source, destination)   #复制文件
             shutil.copytree(source, destination)   #复制文件夹
*移动:shutil.move(source, destination);
*删除:os.unlink()         #删除文件
            os.rmdir()          #删除文件夹,文件夹必须为空
            shutil.rmtree()   #删除文件夹,包含文件夹及文件夹下的所有文件
hello.txt位于"C:\myweb\chapter01"目录下:
>>> import shutil, os
 >>> os.chdir(r'C:\myweb\chapter01')
 >>> os.listdir()
 ['Calculator.php', 'ex1_1.php', 'hello.txt', 'welcome.php', '_notes']
 
一、复制
 1. 复制文件
 #复制hello.txt到"C:\myweb\chapter02"目录下
 >>> shutil.copy('hello.txt', r'C:\myweb\chapter02')
 
 'C:\\myweb\\chapter02\\hello.txt'
 
 #复制hello.txt到"C:\myweb\chapter02"目录并修改名称为hello_01.txt
 >>> shutil.copy('hello.txt', r'C:\myweb\chapter02\hello_01.txt')
 
 'C:\\myweb\\chapter02\\hello_01.txt'
 2. 复制文件夹
 #复制"C:\myweb\chapter01"到"C:\myweb\chapter02"目录下
 >>> shutil.copytree(r'C:\myweb\chapter01', r'C:\myweb\chapter02\chapter01')
 
 'C:\\myweb\\chapter02\\chapter01'
 
 #复制"C:\myweb\chapter01"到"C:\myweb\chapter02"目录下并修改名称为chapter01_bak
 >>> shutil.copytree(r'C:\myweb\chapter01', r'C:\myweb\chapter02\chapter01_bak')
 
 'C:\\myweb\\chapter02\\chapter01_bak'
 二、移动
 1. 移动文件
 #移动hello.txt到"C:\myweb\chapter02"目录下,并修改名称为hello_02.txt
 >>> shutil.move('hello.txt', r'C:\myweb\chapter02\hello_02.txt')
 
 'C:\\myweb\\chapter02\\hello_02.txt'
 2. 移动文件夹
 #创建test文件夹并将其移动至chapter02文件夹下
 >>> os.mkdir(r'C:\myweb\chapter01\test')
 >>> os.path.isdir(r'C:\myweb\chapter01\test')
 
 True
 >>> shutil.move(r'C:\myweb\chapter01\test', r'C:\myweb\chapter02\test')
 
 'C:\\myweb\\chapter02\\test'
 三、 删除
 1. 删除文件
 #删除文件hello_02.txt
 >>> os.chdir(r'C:\myweb\chapter02')
 
 >>> os.listdir(os.getcwd())
 
 ['CalculatorII.php', 'chapter01', 'chapter01_bak', 'circleCal.php', 'hello.txt', 'hello_01.txt', 'hello_02.txt', 'Square.php', 'test']
 >>> os.unlink('hello_02.txt')
 
 >>> os.listdir(os.getcwd())
 
 ['CalculatorII.php', 'chapter01', 'chapter01_bak', 'circleCal.php', 'hello.txt', 'hello_01.txt', 'Square.php', 'test']
 2. 删除空文件夹
 #删除空文件夹test
 >>> os.rmdir(r'./test')
 
 >>> os.listdir(os.getcwd())
 
 ['CalculatorII.php', 'chapter01', 'chapter01_bak', 'circleCal.php', 'hello.txt', 'hello_01.txt', 'Square.php']
 3. 删除非空文件夹
 #删除非空文件夹chapter01
 >>> shutil.rmtree(r'C:\myweb\chapter01')
 
 
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2023-10-11,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档