1. 程式人生 > >Python3之內建模組shutil和shelve

Python3之內建模組shutil和shelve

shutil內建模組

  高階的檔案、資料夾、壓縮包處理模組

['Error', 'ExecError', 'ReadError', 'RegistryError', 'SameFileError', 
'SpecialFileError', '_ARCHIVE_FORMATS', '_BZ2_SUPPORTED', '_LZMA_SUPPORTED', 
'_UNPACK_FORMATS', '__all__', '__builtins__', '__cached__', '__doc__', 
'__file__', '__loader__', '__name__', '__package__'
, '__spec__', '_basename', '_check_unpack_options', '_copyxattr', '_destinsrc', '_ensure_directory', '_find_unpack_format', '_get_gid', '_get_uid', '_make_tarball', '_make_zipfile', '_ntuple_diskusage', '_rmtree_safe_fd', '_rmtree_unsafe', '_samefile', '_unpack_tarfile', '_unpack_zipfile', '_use_fd_functions'
, 'chown', 'collections', 'copy', 'copy2', 'copyfile', 'copyfileobj', 'copymode', 'copystat', 'copytree', 'disk_usage', 'errno', 'fnmatch', 'get_archive_formats', 'get_terminal_size', 'get_unpack_formats', 'getgrnam', 'getpwnam', 'ignore_patterns', 'make_archive', 'move', 'nt', 'os', 'register_archive_format'
, 'register_unpack_format', 'rmtree', 'stat', 'sys', 'tarfile', 'unpack_archive', 'unregister_archive_format', 'unregister_unpack_format', 'which'] >>>

shutil.copyfileobj(fstr,fdst[,length])
將檔案內容拷貝到另一個檔案中,可以部分內容。fstr和fdst指檔案套接字。

import shutil
f1 = open('本節筆記', encoding='utf-8')
f2 = open('筆記2', 'w', encoding='utf-8')
shutil.copyfileobj(f1, f2)

shutil.copyfile(src,dst)

import shutil
shutil.copyfile('筆記2', '筆記3')

shutil.copymode(src, dst)
僅拷貝許可權。內容、組、使用者均不變。

shutil.copystat(src, dst)
拷貝狀態的資訊,包括:mode bits,atime,mtime,flags

shutil.copy(src, dst)
拷貝檔案和許可權

shutil.copy2(src, dst)
拷貝檔案和狀態資訊

shutil.copytree(src, dst, symlinks=False, ignore=None)
遞迴的去拷貝檔案,包括目錄。

import shutil
shutil.copytree('test4', 'new_test4')

test4為目錄名,new_test4自動建立。

shutil.rmtree(path[, ignore_errors[,onerror]])
遞迴刪除檔案

import shutil
shutil.rmtree('new_test4')

shutil.move(src, dst)
遞迴的去移動檔案

shutil.make_archive(base_name, format,…)
建立壓縮包並返回檔案路徑,例如:zip、tar
*base_name:壓縮包的檔名,也可以是壓縮包的路徑。只是檔名時,則儲存至當前目錄,否則儲存至指定路徑,
如:www =>儲存至當前路徑
如: /users/www =>儲存至/users/目錄下
*format:壓縮包種類,’zip’,’tar’,’bztar’,’gztar’
*root_dir:要壓縮的資料夾路徑(預設當前目錄)
*owner:使用者,預設當前使用者
*group:組,預設當前組
*logger:用於記錄日誌,通常時logging.Logger物件

# 將/user/Downloads/test下的檔案打包放置當前程式目錄下
import shutil
ret = shutil.make_archive('www', 'gztar', root_dir='/user/Downloads/test')

shutil對壓縮包的處理時呼叫ZipFile和TarFile兩個模組來進行的。

shelve內建模組

  shelve模組是一個簡單的k,v將記憶體資料通過檔案持久化的模組,可以持久化任何pickle可支援的python資料格式。

寫入檔案

import shelve
import datetime

d = shelve.open('shelve_test')  # 開啟一個檔案

info = {'age': 22, 'job': 'it'}
name = ['tom', 'jerry', 'test']

d['name'] = name
d['info'] = info
d['date'] = datetime.datetime.now()

d.close()

讀取檔案

import shelve
d = shelve.open('shelve_test')  # 開啟一個檔案

print(d.get('name'))
print(d.get('info'))
print(d.get('date'))

d.close()