Python shutil.md
shutil
shutil模塊包括高級文件操作,例如復制和歸檔。
Copying Files
shutil.copyfileobj(fsrc, fdst[, length]):將類似文件的對象fsrc的內容復制到類似文件的對象fdst。整數length(如果給出)是緩沖區大小。具體地,負的長度值意味著復制數據而不使塊中的源數據循環;默認情況下,以塊為單位讀取數據,以避免不受控制的內存消耗。請注意,如果fsrc對象的當前文件位置不為0,則只會復制當前文件位置到文件末尾的內容。
shutil.copyfile(src, dst, *, follow_symlinks=True):將名為src的文件的內容(無元數據)復制到名為dst的文件,然后返回dst。src和dst是以字符串形式給出的路徑名稱。dst必須是完整的目標文件名;請查看shutil.copy()以獲取接受目標目錄路徑的副本。如果src和dst指定相同的文件,則會引發SameFileError。目標位置必須可寫;否則,將引發OSError異常。如果dst已經存在,它將被替換。使用此功能無法復制特殊文件,例如字符或塊設備和管道。如果follow_symlinks為假且src是符號鏈接,則將創建一個新的符號鏈接,而不是復制src指向的文件。
shutil.copy(src, dst, *, follow_symlinks=True):將文件src復制到文件或目錄dst。src和dst應為字符串。如果dst指定目錄,則文件將使用src的基本文件名復制到dst中。返回新創建的文件的路徑。如果follow_symlinks為false,并且src是符號鏈接,則dst將創建為符號鏈接。如果follow_symlinks為true且src是符號鏈接,則dst將是文件的副本src 。copy()復制文件數據和文件的權限模式(請參閱os.chmod())。其他元數據(如文件的創建和修改時間)不會保留。要保留原始文件的所有文件元數據,請改用copy2()。
shutil.copy2(src, dst, *, follow_symlinks=True):與copy()相同,但copy2()也嘗試保留所有文件元數據。當follow_symlinks為false,且src是符號鏈接時,copy2()嘗試從src t5 >符號鏈接到新創建的dst符號鏈接。但是,此功能不適用于所有平臺。在某些或所有功能不可用的平臺上,copy2()將保留其可用的所有元數據; copy2()從不會返回失敗。copy2()使用copystat()復制文件元數據。有關修改符號鏈接元數據的平臺支持的詳細信息,請參閱copystat()。
舉例
copyfile()將源文件內容完全復制給目標文件. 如果沒有寫入目標文件的權限, 會引起IOError. 由于該函數是為了讀取文件內容而打開此輸入文件, 而不管它的類型是什么, 特殊類型的文件使用copyfile()是不能拷貝的, 比如管道文件.
注意:shutil_copyfile.py是需要存在并且訪問路徑正確。輸出如下:
# python shutil_study.py BEFORE: ['shutil_copyfile.py'] AFTER: ['shutil_copyfile.py', 'shutil_copyfile.py.copy']copyfile()底層調用了copyfileobj()函數. 文件名參數傳遞給copyfile()后, 進而將此文件句柄傳遞給copyfileobj(). 第三個可選參數是一個緩沖區長度, 以塊讀入(默認情況下, 一次性讀取整個文件).
import shutil import io import sys import osclass VerboseStringIO(io.StringIO):def read(self, n = -1):next = io.StringIO.read(self, n)print('read({}) got {} bytes'.format(n, len(next)))return nextlorem_ipsum = '''Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Vestibulum aliquam mollis dolor. Donec vulputate nunc ut diam. Ut rutrum mi vel sem. Vestibulum ante ipsum.'''print('Default:') input = VerboseStringIO(lorem_ipsum) output = io.StringIO() shutil.copyfileobj(input, output)print()print('All at once:') input = VerboseStringIO(lorem_ipsum) output = io.StringIO() shutil.copyfileobj(input, output, -1)print()print('Blocks of 256:') input = VerboseStringIO(lorem_ipsum) output = io.StringIO() shutil.copyfileobj(input, output, 256)默認行為是使用大型塊讀取數據。使用-1讀取一次或另一個正整數的所有輸入,可以設置一個特定的塊大小。這個例子使用了幾個不同的塊大小來顯示效果。
Default: read(16384) got 166 bytes read(16384) got 0 bytesAll at once: read(-1) got 166 bytes read(-1) got 0 bytesBlocks of 256: read(256) got 166 bytes read(256) got 0 bytescopy()函數類似于Unix命令cp. 如果目標參數是一個目錄而不是一個文件, 那么在這個目錄中復制一個源文件副本(它與源文件同名). 文件的權限也隨之復制.
import glob import os import shutilos.mkdir('example') print('BEFORE:', glob.glob('example/*'))shutil.copy('shutil_copy.py', 'example')print('AFTER :', glob.glob('example/*'))文件的權限和內容一起復制。輸出:
# python shutil_study.py BEFORE: [] AFTER : ['example/shutil_copy.py']copy2()函數類似于copy(), 但是它將一些元信息, 如文件最后一次被讀取時間和修改時間等, 也復制至新文件中.
import os import shutil import timedef show_file_info(filename):stat_info = os.stat(filename)print(' Mode :', oct(stat_info.st_mode))print(' Created :', time.ctime(stat_info.st_ctime))print(' Accessed:', time.ctime(stat_info.st_atime))print(' Modified:', time.ctime(stat_info.st_mtime))os.mkdir('example') print('SOURCE:') show_file_info('shutil_copy2.py')shutil.copy2('shutil_copy2.py', 'example')print('DEST:') show_file_info('example/shutil_copy2.py')新文件具有與舊版本相同的特性。
# python shutil_study.py SOURCE:Mode : 0o100644Created : Mon Jul 10 00:03:16 2017Accessed: Mon Jul 10 00:03:16 2017Modified: Mon Jul 10 00:03:16 2017 DEST:Mode : 0o100644Created : Mon Jul 10 00:03:26 2017Accessed: Mon Jul 10 00:03:26 2017Modified: Mon Jul 10 00:03:16 2017Copying File Metadata
shutil.copymode(src, dst, *, follow_symlinks=True):將權限位從src復制到dst。文件內容,所有者和組不受影響。src和dst是以字符串形式給出的路徑名稱。
shutil.copystat(src, dst, *, follow_symlinks=True):將權限位,最后訪問時間,上次修改時間和標志從src復制到dst。在Linux上,copystat()也會盡可能復制“擴展屬性”。文件內容,所有者和組不受影響。src和dst是以字符串形式給出的路徑名稱。
舉例
默認情況下, 在Unix下, 一個新創建的文件的權限會根據當前用戶的umask值來設置. 把一個文件的權限復制給另一個文件, 可以使用copymode()函數.
這個示例腳本創建一個要修改的文件,然后使用copymode()將腳本的權限復制到示例文件中。
# python shutil_study.py BEFORE: 0o100444 AFTER : 0o100644復制文件的其他元信息(權限, 最后讀取時間, 最后修改時間)可以使用copystat().
import os import shutil import timedef show_file_info(filename):stat_info = os.stat(filename)print(' Mode :', oct(stat_info.st_mode))print(' Created :', time.ctime(stat_info.st_ctime))print(' Accessed:', time.ctime(stat_info.st_atime))print(' Modified:', time.ctime(stat_info.st_mtime))with open('file_to_change.txt', 'wt') as f:f.write('content') os.chmod('file_to_change.txt', 0o444)print('BEFORE:') show_file_info('file_to_change.txt')shutil.copystat('shutil_copystat.py', 'file_to_change.txt')print('AFTER:') show_file_info('file_to_change.txt')只有與該文件相關聯的權限和日期被復制到copystat()中。
# python shutil_study.py BEFORE:Mode : 0o100444Created : Mon Jul 10 00:20:02 2017Accessed: Mon Jul 10 00:20:02 2017Modified: Mon Jul 10 00:20:02 2017 AFTER:Mode : 0o100644Created : Mon Jul 10 00:20:02 2017Accessed: Mon Jul 10 00:12:15 2017Modified: Mon Jul 10 00:12:15 2017Working With Directory Trees
shutil.ignore_patterns(*patterns):此工廠函數創建一個函數,可用作copytree()的忽略參數的可調用函數,忽略與glob類型模式。
shutil.copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2, ignore_dangling_symlinks=False):遞歸地復制以src為根的整個目錄樹,返回目標目錄。由dst命名的目標目錄不能已經存在;它將被創建以及缺少父目錄。使用copystat()復制目錄的權限和時間,使用shutil.copy2()復制單個文件。如果符號鏈接為真,則源樹中的符號鏈接在新樹中表示為符號鏈接,并且原始鏈接的元數據將被復制到平臺允許的范圍內;如果為false或省略,鏈接文件的內容和元數據將復制到新樹。當符號鏈接為false時,如果符號鏈接指向的文件不存在,則在Error異常中引發的錯誤列表中將添加一個異常復制過程。如果要凍結此異常,可以將可選的ignore_dangling_symlinks標志設置為true。請注意,此選項對不支持os.symlink()的平臺沒有影響。
shutil.rmtree(path, ignore_errors=False, οnerrοr=None):刪除整個目錄樹; 路徑必須指向目錄(而不是指向目錄的符號鏈接)。如果ignore_errors為true,則刪除失敗導致的錯誤將被忽略;如果為false或省略,則通過調用onerror指定的處理程序處理這些錯誤,如果省略,則引發異常。
shutil.move(src, dst, copy_function=copy2):遞歸地將文件或目錄(src)移動到另一個位置(dst),并返回目標。如果目標是現有目錄,則src在該目錄中移動。如果目標已經存在,但不是目錄,根據os.rename()語義,它可能會被覆蓋。如果目標位于當前文件系統上,則使用os.rename()。否則,使用copy_function將src復制到dst,然后刪除。在符號鏈接的情況下,指向src的目標的新符號鏈接將在dst中創建或創建,src將被刪除。如果給出copy_function,它必須是一個可調用,它接受兩個參數src和dst,并且將用于復制src 到dest如果os.rename()不能使用。如果源是目錄,則調用copytree(),將其傳遞給copy_function()。默認的copy_function是copy2()。使用copy()作為copy_function允許移動成功,當不可能也復制元數據,而不復制任何元數據。
舉例
shutil模塊包含3個操作目錄樹的函數. 使用copytree()來復制目錄, 它會遞歸復制整個目錄結構. 目標目錄必須不存在. 其中, symlinks參數控制符號鏈接是否作為鏈接或文件被復制, 默認是將其內容復制成一個新文件. 如果此選項為true, 新的鏈接會在目標目錄樹中創建.
符號鏈接參數控制符號鏈接是否被復制為鏈接或文件。缺省情況是將內容復制到新文件中。如果選項是true,則在目標樹中創建新的符號鏈接。
# python shutil_study.py BEFORE: []AFTER: ['/tmp/example/shutil_copymode.py','/tmp/example/testdata.csv','/tmp/example/example','/tmp/example/testout.csv','/tmp/example/csv_study.py','/tmp/example/unicode_chars','/tmp/example/file_to_change.txt','/tmp/example/shutil_copyfile.py','/tmp/example/testdata.pipes','/tmp/example/os_path_study.py','/tmp/example/shutil_copy2.py','/tmp/example/shutil_copyfile.py.copy','/tmp/example/shutil_copystat.py','/tmp/example/testdata_1.csv','/tmp/example/shutil_study.py','/tmp/example/shutil_copy.py']copytree()接受兩個可調用的參數來控制它的行為。 使用每個目錄或子目錄的名稱以及目錄的內容列表來調用ignore參數。 它應該返回被復制的項目的列表。調用copy_function參數用來實際復制文件。
import glob import pprint import shutildef verbose_copy(src, dst):print('copying\n {!r}\n to {!r}'.format(src, dst))return shutil.copy2(src, dst)print('BEFORE:') pprint.pprint(glob.glob('/tmp/example/*')) print()shutil.copytree('../shutil', '/tmp/example',copy_function=verbose_copy,ignore=shutil.ignore_patterns('*.py'), )print('\nAFTER:') pprint.pprint(glob.glob('/tmp/example/*'))在該示例中,ignore_patterns()用于創建一個忽略函數來跳過復制Python源文件。 verbose_copy()打印復制文件的名稱,然后使用copy2()(默認復制功能)來創建副本。輸出:
BEFORE: []copying'../shutil/example.out'to '/tmp/example/example.out' copying'../shutil/file_to_change.txt'to '/tmp/example/file_to_change.txt' copying'../shutil/index.rst'to '/tmp/example/index.rst'AFTER: ['/tmp/example/example','/tmp/example/example.out','/tmp/example/file_to_change.txt','/tmp/example/index.rst']要刪除一個目錄及其內容,請使用rmtree()。
import glob import pprint import shutilprint('BEFORE:') pprint.pprint(glob.glob('/tmp/example/*'))shutil.rmtree('/tmp/example')print('\nAFTER:') pprint.pprint(glob.glob('/tmp/example/*'))默認情況下,錯誤會被作為異常進行處理,但是如果第二個參數是true,則可以忽略它,并且在第三個參數中可以提供一個特殊的錯誤處理函數。輸出:
BEFORE: ['/tmp/example/example','/tmp/example/example.out','/tmp/example/file_to_change.txt','/tmp/example/index.rst']AFTER: []要將文件或目錄從一個位置移動到另一個位置,請使用move()。
import glob import shutilwith open('example.txt', 'wt') as f:f.write('contents')print('BEFORE: ', glob.glob('example*'))shutil.move('example.txt', 'example.out')print('AFTER : ', glob.glob('example*'))該語義類似于Unix命令mv的語義。如果源和目標在同一個文件系統中,則將源重新命名。否則,源將被復制到目標,然后源被刪除。輸出:
BEFORE: ['example.txt'] AFTER : ['example.out']Finding Files
shutil.which(cmd, mode=os.F_OK | os.X_OK, path=None):返回可執行文件的路徑,如果給定的cmd被調用,它將運行。如果不調用cmd,則返回None。mode是傳遞給os.access()的權限掩碼,默認情況下確定文件是否存在和可執行。當未指定路徑時,將使用os.environ()的結果,返回“PATH”值或返回os.defpath
舉例
which()函數掃描查找命名文件的搜索路徑。 典型的用例是在環境變量PATH中定義的shell的搜索路徑上找到一個可執行程序。
如果沒有找到匹配搜索參數的文件,那么which()返回None。輸出:
/Users/dhellmann/Library/Python/3.5/bin/virtualenv /Users/dhellmann/Library/Python/3.5/bin/tox Nonewhich()根據文件具有的權限以及要檢查的搜索路徑接受參數進行過濾。 path參數默認為os.environ('PATH'),但可以是包含以os.pathsep分隔的目錄名的任何字符串。 mode參數應該是匹配文件權限的位掩碼。 默認情況下,掩碼將查找可執行文件,但以下示例使用可讀位掩碼和備用搜索路徑來查找配置文件。
import os import shutilpath = os.pathsep.join(['.',os.path.expanduser('~/pymotw'), ])mode = os.F_OK | os.R_OKfilename = shutil.which('config.ini',mode=mode,path=path, )print(filename)仍然有競爭條件以這種方式搜索可讀文件,因為在找到文件和實際嘗試使用文件之間的時間內,文件可以被刪除或其權限可以更改。輸出:
$ touch config.ini $ python3 shutil_which_regular_file.py./config.iniArchives
shutil.get_archive_formats():返回支持的歸檔格式列表。返回序列的每個元素都是元組(名稱, 描述)。
shutil.make_archive(base_name, format[, root_dir[, base_dir[, verbose[, dry_run[, owner[, group[, logger]]]]]]]):創建歸檔文件(例如zip或tar)并返回其名稱。
- base_name是要創建的文件的名稱,包括路徑,減去任何特定于格式的擴展名。format is the archive format: one of “zip”, “tar”, “bztar” (if the bz2 module is available), “xztar” (if the lzma module is available) or “gztar”.
- root_dir是將成為歸檔的根目錄的目錄;例如,在創建歸檔之前,我們通常將chdir插入到root_dir中。
- base_dir是我們開始歸檔的目錄;即:base_dir將是歸檔中所有文件和目錄的公共前綴。
- root_dir和base_dir都默認為當前目錄。
- 如果dry_run為true,則不創建歸檔,但將執行的操作記錄到logger。
- 所有者和組用于創建tar存檔。默認情況下,使用當前所有者和組。
- logger必須是與 PEP 282兼容的對象,通常為logging.Logger的實例。
shutil.get_unpack_formats():返回分拆的所有注冊格式的列表。返回序列的每個元素都是元組(名稱, 擴展名, 描述)。
默認情況下,shutil提供以下格式:
- gztar:gzip的tar文件
- bztar:bzip2'ed tar文件(如果bz2模塊可用)。
- xztar:xz'ed tar文件(如果lzma模塊可用)。
- tar:未壓縮的tar文件
- zip:ZIP文件
舉例
Python的標準庫包含許多用于管理諸如tar文件和zipfile等歸檔文件的模塊。在shutil中,還有一些用于創建和提取存檔的高級功能。getarchiveformat()返回當前系統支持的格式的名稱和描述序列。
所支持的格式取決于哪些模塊和底層庫可用,因此這個示例的輸出可能基于運行的位置而發生變化。
bztar: bzip2'ed tar-file gztar: gzip'ed tar-file tar : uncompressed tar file xztar: xz'ed tar-file zip : ZIP file使用makearchive()來創建一個新的歸檔文件。其輸入的目的是為了最好地支持對整個目錄及其所有內容進行遞歸的歸檔。默認情況下,它使用當前的工作目錄,以便所有的文件和子目錄都出現在歸檔的頂層。要更改該行為,請使用rootdir參數移動到文件系統和basedir參數的一個新的相對位置,以指定要添加到歸檔的目錄。
import logging import shutil import sys import tarfilelogging.basicConfig(format='%(message)s',stream=sys.stdout,level=logging.DEBUG, ) logger = logging.getLogger('pymotw')print('Creating archive:') shutil.make_archive('example', 'gztar',root_dir='..',base_dir='shutil',logger=logger, )print('\nArchive contents:') with tarfile.open('example.tar.gz', 'r') as t:for n in t.getnames():print(n)這個示例從源目錄中開始,用于shutil的示例,并在文件系統中提升一個級別,然后將shutil目錄添加到用gzip壓縮的tar存檔文件中。日志模塊被配置為從makearchive()中顯示它正在做的事情。
Creating archive: changing into '..' Creating tar archive changing back to '...'Archive contents: shutil shutil/config.ini shutil/example.out shutil/file_to_change.txt shutil/index.rst shutil/shutil_copy.py shutil/shutil_copy2.py shutil/shutil_copyfile.py shutil/shutil_copyfileobj.py shutil/shutil_copymode.py shutil/shutil_copystat.py shutil/shutil_copytree.py shutil/shutil_copytree_verbose.py shutil/shutil_disk_usage.py shutil/shutil_get_archive_formats.py shutil/shutil_get_unpack_formats.py shutil/shutil_make_archive.py shutil/shutil_move.py shutil/shutil_rmtree.py shutil/shutil_unpack_archive.py shutil/shutil_which.py shutil/shutil_which_regular_file.pyshutil維護一個可以在當前系統上解壓縮的格式的注冊表,可以通過getunpackformat()訪問。
import shutilfor format, exts, description in shutil.get_unpack_formats():print('{:<5}: {}, names ending in {}'.format(format, description, exts))這個注冊表不同于創建存檔的注冊表,因為它還包含用于每個格式的公共文件擴展,以便提取存檔的函數可以根據文件擴展來猜測使用哪種格式。
bztar: bzip2'ed tar-file, names ending in ['.tar.bz2', '.tbz2'] gztar: gzip'ed tar-file, names ending in ['.tar.gz', '.tgz'] tar : uncompressed tar file, names ending in ['.tar'] xztar: xz'ed tar-file, names ending in ['.tar.xz', '.txz'] zip : ZIP file, names ending in ['.zip']使用unpackarchive()提取存檔,傳遞存檔文件名,并選擇應該提取的目錄。如果沒有給出目錄,則使用當前目錄。
import pathlib import shutil import sys import tempfilewith tempfile.TemporaryDirectory() as d:print('Unpacking archive:')shutil.unpack_archive('example.tar.gz',extract_dir=d,)print('\nCreated:')prefix_len = len(d) + 1for extracted in pathlib.Path(d).rglob('*'):print(str(extracted)[prefix_len:])在這個示例中,unpackarchive()能夠確定存檔的格式,因為文件名以tar.gz結尾,這個值在解壓格式注冊表中與gztar格式相關聯。
Unpacking archive:Created: shutil shutil/config.ini shutil/example.out shutil/file_to_change.txt shutil/index.rst shutil/shutil_copy.py shutil/shutil_copy2.py shutil/shutil_copyfile.py shutil/shutil_copyfileobj.py shutil/shutil_copymode.py shutil/shutil_copystat.py shutil/shutil_copytree.py shutil/shutil_copytree_verbose.py shutil/shutil_disk_usage.py shutil/shutil_get_archive_formats.py shutil/shutil_get_unpack_formats.py shutil/shutil_make_archive.py shutil/shutil_move.py shutil/shutil_rmtree.py shutil/shutil_unpack_archive.py shutil/shutil_which.py shutil/shutil_which_regular_file.pyFile System Space
shutil.disk_usage(path):將給定路徑的磁盤使用情況統計信息作為named tuple返回總計,使用和免費是總的,已用和可用空間的量,以字節為單位。
舉例
在執行一個可能耗盡該空間的長時間運行的操作之前,檢查本地文件系統以查看有多少空間是有用的。diskusage()返回一個包含總空間的元組,當前正在使用的數量,以及剩余的空閑量。
disk_usage()返回的值是字節數,因此示例程序將它們轉換為更可讀的單元,然后再打印它們。
Total: 499.42 GB 465.12 GiB Used : 246.68 GB 229.73 GiB Free : 252.48 GB 235.14 GiB轉載于:https://www.cnblogs.com/cuchadanfan/p/7148509.html
總結
以上是生活随笔為你收集整理的Python shutil.md的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《Spring》(十六)---- JDB
- 下一篇: 《面向对象程序设计》课程作业二