一、高級文件處理shutil模塊:
a. 簡單文件操作:
1. 將文件內容cope到另一個文件中:shutil.copyfileobj(open('test_t.txt','r'),ope('test.txt','a'));
2. cope文件:shutil.copefile('test.txt','test_t.txt');
3. cope權限:shutil.copymode('test.txt','test_t.txt');
4. cope狀態信息:shutil.copystat('test.txt','test_t.txt');
5. cope文件和權限:shutil.copy('test.txt','test_t.txt');
6. cope文件和狀態信息:shutil.copy2('test.txt','test_t.txt')
7. cope文件包忽略編譯文件和臨時文件:shutil.copytree('shutil_test','test',ignore=shutil.ignore_patterns('*.pyc','tmp*'));
8. 遞歸的刪除文件:shutil.rmtree('test');
9. 移動整個文件目錄和文件:shutil.move('random_test','shutil_test');
b. 文件壓縮操作:
1. shutil.make_archive(base_name,format,root_dir...)
[ ret2 = shutil.make_archive("/tmp_test/data_bak", 'zip', root_dir='/data1') # 將 /data1下的文件打包放置 /tmp_test/目錄下 ];
---> base_name:壓縮包的名稱、路徑;
--->format:‘zip’/'tar'/bztar'/'gztar';
--->root_dir:要壓縮的文件路徑(默認當前目錄);
二、文件壓縮,解壓縮zipfile模塊:
1. 壓縮:zipfile_handle = zipfile.ZipFile('zipfile_test.zip','w')--->zipfile_handle.write('hash_module_test.py')--->zipfile_handle.close();
2. 解壓:zipfile_handle = zipfile.ZipFile('zipfile_test.zip','r')--->zipfile_handle.extractall('..')--->zipfile_handle.close();
三、文件打包,解包tarfile模塊:
1. 打包:tarfile_handle = tarfile.open('C:\\a\\c\\tarfile_test.tar','w')--->tarfile_handle.add('random_test.py',arcname='ran_test.bak')--->tarfile_handle.close();
2. 解包:tarfile_handle = tarfile.open('C:\\a\\c\\tarfile_test.tar','r')--->tarfile_handle.extractall(C:\\a\\c')--->tarfile_handle.close();