Python文件操作模块shutil

shutil

shutil.copyfileobj(fsrc, fdst[, length])

  • 将类似文件的对象fsrc的内容复制到类似文件的对象fdst。
import shutil

f1 = open('1.txt','r',encoding='utf-8')
f2 = open('2.txt', 'w',encoding='utf-8')
shutil.copyfileobj(f1, f2)
f1.close()
f2.close()

shutil.copyfile(src, dst, *, follow_symlinks=True)

  • 将名为src的文件的内容(无元数据)复制到名为dst的文件,然后返回dst。
import shutil

shutil.copyfile('1.txt', '2.txt')

元数据概念 

元数据(Meta Date),关于数据的数据或者叫做用来描述数据的数据或者叫做信息的信息。

通常情况下元数据可以分为以下三类:固有性元数据、管理元数据、描述性元数据。 固有性元数据;与事物构成有关的元数据。 管理性元数据;与事物处理方式有关的元数据。 描述性元数据;与事物本质有关的元数据。

 

shutil.copymode(src, dst, *, follow_symlinks=True)

  • 将权限位从src复制到dst。文件内容,所有者和组不受影响。

shutil.copystat(src, dst, *, follow_symlinks=True)

  • 将权限位,最后访问时间,上次修改时间和标志从src复制到dst。
import shutil

shutil.copystat('1.txt', '2.txt')

shutil.copy(src, dst, *, follow_symlinks=True)

  • 将文件src复制到文件或目录dst。src和dst应为字符串。如果dst指定目录,则文件将使用src的基本文件名复制到dst中。返回新创建的文件的路径。

shutil.copy2(src, dst, *, follow_symlinks=True)

  • 与copy()相同,但copy2()也尝试保留所有文件元数据。

shutil.copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2, ignore_dangling_symlinks=False)

  • 递归地复制以src为根的整个目录树,返回目标目录。由dst命名的目标目录不能已经存在;它将被创建以及缺少父目录。使用copystat()复制目录的权限和时间,使用shutil.copy2()复制单个文件。
  • 下例子会将test文件夹下的所有文件及文件夹递归复制生成test1.
import shutil

shutil.copytree('test', 'test1')

shutil.rmtree(path, ignore_errors=False, onerror=None)

  • 删除整个目录树; 路径必须指向目录(而不是指向目录的符号链接)。如果ignore_errors为true,则删除失败导致的错误将被忽略;如果为false或省略,则通过调用onerror指定的处理程序处理这些错误,如果省略,则引发异常。

shutil.move(src, dst, copy_function=copy2)

  • 递归地将文件或目录(src)移动到另一个位置(dst),并返回目标。

shutil.disk_usage(path)

  • 将给定路径的磁盘使用情况统计信息作为named tuple返回总计,使用和all free的,已用和可用空间的量,以字节为单位。
import shutil

name_touple = shutil.disk_usage(r'E:\Atom\files\app')
print(name_touple)

PS E:\Atom\files\app> python .\ex_shutil.py
usage(total=536869859328, used=177328979968, free=359540879360)

shutil.chown(path, user=None, group=None)

  • 更改给定路径的所有者用户和/或组。

shutil.which(cmd, mode=os.F_OK | os.X_OK, path=None)

  • 返回可执行文件的路径,如果给定的cmd被调用,它将运行。如果不调用cmd,则返回None。

猜你喜欢

转载自www.cnblogs.com/Frange/p/9258445.html