一、高级文件处理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();