您的位置:首页 > 编程语言 > Python开发

Python组织文件: shutil, os, send2trash 模块

2020-03-23 18:38 561 查看

复制文件
shutil.copy(source, destination)

shutil.copy(source, destination)
将source处的文件复制到路径destination 处的文件夹。

os.chdir('C:\\')
#  part1 文件夹存在时,hello.txt 被复制到 C:\part1 中
#  part1 文件夹不存在时,hello.txt 被复制为 part1 文件,没有 .txt 后缀
shutil.copy('hello.txt', 'part1')
#  helloworld.txt 不存在时,hello.txt 被复制,名为 helloworld.txt
#  helloworld.txt 存在时,helloworld.txt 被 hello.txt 覆写
shutil.copy('hello.txt','helloworld.txt')

复制文件夹
shutil.copytree(source, destination)

shutil.copytree(source, destination)
复制整个文件夹,以及它包含的文件夹和文件。

## 如果 destination 目录不存在, 系统会新建该文件夹
shutil.copytree('.\\EnglishSongs','.\\HeadFirstPython')
## 如果 source 目录,不存在,会报错
#  FileNotFoundError: [WinError 3] 系统找不到指定的路径。: '.\\EnglishSongs'
shutil.copytree('.\\EnglishSongs','.\\HeadFirstPython')

移动文件和文件夹
shutil.move(source, destination)

shutil.move(source, destination)
将路径source 处的文件和文件夹移动到路径 destination 处。

#  destination 文件夹存在,且文件夹中不存在 A Whole New World.txt 时, A Whole New World.txt 被移动到 EnglishSongs 中
#  destination 文件夹存在,且文件夹中已存在 A Whole New World.txt 时, EnglishSongs 中 A Whole New World.txt 被新文件覆写
shutil.move('A Whole New World.txt', '.\\HeadFirstPython\\EnglishSongs')
# destination 文件夹不存在时, EnglishSongs 被作为一个文件名,A Whole New World.txt文件被移动到 .\\HeadFirstPython 并改名为 EnglishSongs(没有 .txt
# 的文本文件)
shutil.move('A Whole New World.txt', '.\\HeadFirstPython\\EnglishSongs')
# destination 为一个文件名时,source 文件被移动并改名
shutil.move('phonemail.txt', '.\\HeadFirstPython\\phone_email.txt')
#  source 为一个文件夹时,EnglishSongs 移动到父文件夹中
#  destination 中存在同名文件夹时,程序报错
shutil.move('..\EnglishSongs','.')

永久删除文件和文件夹
shutil.rmtree(path)

shutil.rmtree(path)
可以删除一个文件夹及其中所有的内容。

# 删除 path 处所有的文件和文件夹
shutil.rmtree(path)

os.unlink(path)
方法永久删除文件
os.rmdir(path)
方法永久删除空文件夹

# 删除 path 处的文件
os.unlink(path)
# 删除 path 处的文件夹,该文件夹必须为空
os.rmdir(path)

一个删除.txt文件的例子:

#! python3
# 删除 quizfile0.txt -- quizfile34.txt,answerfile0.txt -- answerfile34.txt
import shutil
import os
import re

txtRegex = re.compile(r'(((quizfile)|(answerfile))(\d+)(\.txt))')
allTxtFile = txtRegex.findall(' '.join(os.listdir('C:\\HeadFirstPython')))

for afile in allTxtFile:
afilename = list(afile)[0]
os.unlink(afilename)
# print(afilename)

可恢复的删除
send2trash(path)

send2trash(path)
删除文件并将文件发送至回收站

#  删除文件
send2trash.send2trash('phone_email.txt')
#  删除文件夹
send2trash.send2trash('.\EnglishSongs')
  • 点赞
  • 收藏
  • 分享
  • 文章举报
yuanyuan1900 发布了5 篇原创文章 · 获赞 0 · 访问量 99 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: