os 模块

  • os.path.join(), os.path.getsize(path)
  • os.getcwd(), os.chdir(path), os.makedirs(path), os.listdir(path),
  • os.path.abspath(path), os.path.isabs(path), os.path.relpath(path,start) (返回从 start 到 path 的相对路径)
  • os.path.dirname(path), os.path.basename(path)
  • os.path.exists(path), os.path.isfile(path), os.path.isdir(path)

shutil 模块

  • shutil.copy(src,dest) (copy src file to dest dir or to dest file)
  • shutil.copytree(src,dest) (copy dir from src to dest)
  • shutil.move(src, dest) (if dest dir not exist, will be thought as file)
  • shutil.rmtree(path) (rm -rf path)
  • os.unlink(path) rm path file
  • os.rmdir(path) rm path dir, path dir must empty
  • send2trash.send2trash(path) mv file/dir to system trash box, not delete
import shutil
shutil.move('root/test/tmp.txt', 'root/eggs')  # root/eggs 文件夹不存在,被看作文件名

遍历目录

import os
for dirname, subdirs, filenames in os.walk(path):
   print('current dir is {}'.format(dirname))
   print('current sub dir are {}'.format(subdirs))
   print('current files is {}'.format(filenames))

zipfile 模块

  • 简单查看压缩包内的信息
import zipfile, os
with zipfile.ZipFile('example.zip') as exampleZip:
	exampleZip.namelist()   # 返回所有文件和文件夹的列表
	spamInfo = exampleZip.getinfo('spam.txt')
	spamInfo.file_size
	spamInfo.compress_size
# exampleZip = zipfile.ZipFile('example.zip')
# exampleZip.close()
  • 解压压缩包内的内容
# 解压整个压缩包,若 path 不填写,则解压到当前目录下
with zipfile.ZipFile('example.zip') as exampleZip:
	exampleZip.extractall(path)
 
# 解压特定文件,若第二个参数存在但文件夹不存在,会自动创建
with zipfile.ZipFile('example.zip') as exampleZip:
	exampleZip.extract('spam.txt')
	exampleZip.extract('spam.txt', 'User/Projects')
  • 创建和添加到 zip 文件
with zipfile.ZipFile('example.zip', 'w') as exampleZip: # 或者使用 `a` append 模式
	exampleZip.write('spam.txt', compres_type=zipfile.ZIP_DEFLATED)