python 删除文件、清空目录的方法总结 / shutil 模块介绍python 删除文件、清空目录的方法总结 / shutil 模块介绍python 删除文件、清空目录的方法总结 / shutil 模块介绍python 删除文件、清空目录的方法总结 / shutil 模块介绍
  • 首页
  • 博客
  • 文件
  • 书签
  • 分析
  • 登录
Search
Generic filters

python 删除文件、清空目录的方法总结 / shutil 模块介绍

Published by admin at 2022年3月18日
Categories
  • Python
Tags

Python os.remove() 方法

os.remove() 方法用于删除指定路径的文件。如果指定的路径是一个目录,将抛出OSError。

在Unix, Windows中有效

以下实例演示了 remove() 方法的使用:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os, sys

# 列出目录
print "目录为: %s" %os.listdir(os.getcwd())

# 移除
os.remove("aa.txt")

# 移除后列出目录
print "移除后 : %s" %os.listdir(os.getcwd())

执行以上程序输出结果为:

目录为:
[ 'a1.txt','aa.txt','resume.doc' ]
移除后 : 
[ 'a1.txt','resume.doc' ]

Python os.removedirs() 方法

os.removedirs() 方法用于递归删除目录。像rmdir(), 如果子文件夹成功删除, removedirs()才尝试它们的父文件夹,直到抛出一个error(它基本上被忽略,因为它一般意味着你文件夹不为空)。

以下实例演示了 removedirs() 方法的使用:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os, sys

# 列出目录
print "目录为: %s" %os.listdir(os.getcwd())

# 移除
os.removedirs("/test")

# 列出移除后的目录
print "移除后目录为:" %os.listdir(os.getcwd())

执行以上程序输出结果为:

目录为:
[  'a1.txt','resume.doc','a3.py','test' ]
移除后目录为:
[  'a1.txt','resume.doc','a3.py' ]

Python os.rmdir() 方法

os.rmdir() 方法用于删除指定路径的目录。仅当这文件夹是空的才可以, 否则, 抛出OSError。

以下实例演示了 rmdir() 方法的使用:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os, sys

# 列出目录
print "目录为: %s"%os.listdir(os.getcwd())

# 删除路径
os.rmdir("mydir")

# 列出重命名后的目录
print "目录为: %s" %os.listdir(os.getcwd())

执行以上程序输出结果为:

目录为:
[  'a1.txt','resume.doc','a3.py','mydir' ]
目录为:
[  'a1.txt','resume.doc','a3.py' ]

Python os.unlink() 方法

os.unlink() 方法用于删除文件,如果文件是一个目录则返回一个错误。

以下实例演示了 unlink() 方法的使用:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os, sys

# 列出目录
print "目录为: %s" %os.listdir(os.getcwd())

os.unlink("aa.txt")

# 删除后的目录
print "删除后的目录为 : %s" %os.listdir(os.getcwd())

执行以上程序输出结果为:

目录为:
[ 'a1.txt','aa.txt','resume.doc']
删除后的目录为 : 
[ 'a1.txt','resume.doc' ]

其他的总结

1、remove() 同 unlink() 的功能是一样的

在Windows系统中,删除一个正在使用的文件,将抛出异常。在Unix中,目录表中的记录被删除,但文件的存储还在。

#使用os.unlink()和os.remove()来删除文件
#!/user/local/bin/python2.7
# -*- coding:utf-8 -*-
import os
my_file = 'D:/text.txt'
if os.path.exists(my_file):
    #删除文件,可使用以下两种方法。
    os.remove(my_file)
    #os.unlink(my_file)
else:
    print 'no such file:%s'%my_file

2、递归删除目录和文件的方法(类似DOS命令DeleteTree):
复制代码 代码如下:

import os
for root, dirs, files in os.walk(top, topdown=False):
    for name in files:
        os.remove(os.path.join(root, name))
    for name in dirs:
        os.rmdir(os.path.join(root, name))

3、Python清空指定文件夹下所有文件的方法:
这个需求很简单:需要在执行某些代码前清空指定的文件夹,如果直接用os.remove(),可能出现因文件夹中文件被占用而无法删除,解决方法也很简单,先强制删除文件夹,再重新建同名文件夹即可:

import shutil  
shutil.rmtree('要清空的文件夹名')  
os.mkdir('要清空的文件夹名')

如果想把一个文件从一个文件夹移动到另一个文件夹,并同时重命名,用shutil也很简单:

shutil.move('原文件夹/原文件名','目标文件夹/目标文件名')

shutil模块介绍

高级的 文件、文件夹、压缩包 处理模块

shutil.copyfileobj(fsrc, fdst[, length])
将文件内容拷贝到另一个文件中

1 import shutil
2  
3 shutil.copyfileobj(open('old.xml','r'), open('new.xml', 'w'))

 

shutil.copyfile(src, dst)
拷贝文件

1 shutil.copyfile('f1.log', 'f2.log') #目标文件无需存在

 

shutil.copymode(src, dst)
仅拷贝权限。内容、组、用户均不变

1 shutil.copymode('f1.log', 'f2.log') #目标文件必须存在

 

shutil.copystat(src, dst)
仅拷贝状态的信息,包括:mode bits, atime, mtime, flags

1 shutil.copystat('f1.log', 'f2.log') #目标文件必须存在

 

shutil.copy(src, dst)
拷贝文件和权限

1 import shutil
2  
3 shutil.copy('f1.log', 'f2.log')

 

shutil.copy2(src, dst)
拷贝文件和状态信息

1 import shutil
2  
3 shutil.copy2('f1.log', 'f2.log')

 

shutil.ignore_patterns(*patterns)
shutil.copytree(src, dst, symlinks=False, ignore=None)
递归的去拷贝文件夹

1 import shutil
2  
3 shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*')) #目标目录不能存在,注意对folder2目录父级目录要有可写权限,ignore的意思是排除

import shutil

shutil.copytree('f1', 'f2', symlinks=True, ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))

'''
通常的拷贝都把软连接拷贝成硬链接,即对待软连接来说,创建新的文件
'''

shutil.rmtree(path[, ignore_errors[, onerror]])
递归的去删除文件

1 import shutil
2  
3 shutil.rmtree('folder1')

 

shutil.move(src, dst)
递归的去移动文件,它类似mv命令,其实就是重命名。

1 import shutil
2  
3 shutil.move('folder1', 'folder3')

 

shutil.make_archive(base_name, format,...)

创建压缩包并返回文件路径,例如:zip、tar

创建压缩包并返回文件路径,例如:zip、tar

    • base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,
      如 data_bak                       =>保存至当前路径
      如:/tmp/data_bak =>保存至/tmp/
    • format: 压缩包种类,“zip”, “tar”, “bztar”,“gztar”
    • root_dir: 要压缩的文件夹路径(默认当前目录)
    • owner: 用户,默认当前用户
    • group: 组,默认当前组
    • logger: 用于记录日志,通常是logging.Logger对象
      #将 /data 下的文件打包放置当前程序目录
      import shutil
      ret = shutil.make_archive("data_bak", 'gztar', root_dir='/data')
        
        
      #将 /data下的文件打包放置 /tmp/目录
      import shutil
      ret = shutil.make_archive("/tmp/data_bak", 'gztar', root_dir='/data')

      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(path='.')
      z.close()
      
      
      import tarfile
      
      # 压缩
      >>> 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()

      tarfile压缩解压缩

       

发表回复 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注

Categories

  • 猫
  • Python
  • MySQL
  • Django
  • Html/CSS
  • JavaScript
  • Vue
  • RegExp
  • php
  • Practice
  • Virtualization
  • Linux
  • Windows
  • Android
  • NAS
  • Software
  • Hardware
  • Network
  • Router
  • Office
  • WordPress
  • SEO
  • English
  • Games
  • Recipes
  • living
  • Memorandum
  • Essays
  • 未分类

归档

©2015-2022 Alaica Blog support@alaica.com