130、shutil 模块:高级文件操作
本文最后更新于 68 天前,其中的信息可能已经过时,如有错误请发送邮件到wuxianglongblog@163.com

shutil 模块:高级文件操作

import shutil
import os

shutilPython 中的高级文件操作模块。

复制文件

with open("test.file", "w") as f:
    pass

print "test.file" in os.listdir(os.curdir)
True

shutil.copy(src, dst) 将源文件复制到目标地址:

shutil.copy("test.file", "test.copy.file")

print "test.file" in os.listdir(os.curdir)
print "test.copy.file" in os.listdir(os.curdir)
True
True

如果目标地址中间的文件夹不存在则会报错:

try:
    shutil.copy("test.file", "my_test_dir/test.copy.file")
except IOError as msg:
    print msg
[Errno 2] No such file or directory: 'my_test_dir/test.copy.file'

另外的一个函数 shutil.copyfile(src, dst)shutil.copy 使用方法一致,不过只是简单复制文件的内容,并不会复制文件本身的读写可执行权限,而 shutil.copy 则是完全复制。

复制文件夹

将文件转移到 test_dir 文件夹:

os.renames("test.file", "test_dir/test.file")
os.renames("test.copy.file", "test_dir/test.copy.file")

使用 shutil.copytree 来复制文件夹:

shutil.copytree("test_dir/", "test_dir_copy/")

"test_dir_copy" in os.listdir(os.curdir)
True

删除非空文件夹

os.removedirs 不能删除非空文件夹:

try:
    os.removedirs("test_dir_copy")
except Exception as msg:
    print msg
[Errno 39] Directory not empty: 'test_dir_copy'

使用 shutil.rmtree 来删除非空文件夹:

shutil.rmtree("test_dir_copy")

移动文件夹

shutil.move 可以整体移动文件夹,与 os.rename 功能差不多。

产生压缩文件

查看支持的压缩文件格式:

shutil.get_archive_formats()
[('bztar', "bzip2'ed tar-file"),
 ('gztar', "gzip'ed tar-file"),
 ('tar', 'uncompressed tar file'),
 ('zip', 'ZIP file')]

产生压缩文件:

shutil.make_archive(basename, format, root_dir)

shutil.make_archive("test_archive", "zip", "test_dir/")
'/home/lijin/notes-python/11. useful tools/test_archive.zip'

清理生成的文件和文件夹:

os.remove("test_archive.zip")
shutil.rmtree("test_dir/")
谨此笔记,记录过往。凭君阅览,如能收益,莫大奢望。
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇