Python programming Quick Start Chapter 1 practical project reference answers, python Quick Start
This chapter introduces the use of the shutil and zipfile modules. Let's take a look at these two modules.
1. shutil Module
The shutil module is mainly used to process files or folders, including copying, moving, renaming, and deleting files. The shutil module mainly includes the following functions:
1. Copy files and folders
The shutil module provides two functions: shutil. copy () and shutil. copytree ()
Syntax format of shutil. copy:
copy(src, dst)
Purpose:
Copy the file at src to the dst path, where src and dst are strings. If dst is a file name, it will serve as the new name of the file to be copied. It is equivalent to copying the file from the original path to the new path and renaming it.
Example:
Copy/etc/my. cnf to/root/mysql
In [12]: import shutilIn [13]: shutil.copy('/etc/my.cnf','/root/mysql/')Out[13]: '/root/mysql/my.cnf'In [15]: ll /root/mysql/total 4-rw-r--r--. 1 root 960 Apr 22 16:57 my.cnf
Copy/etc/my. cnf to/root/mysql and change the name to mysql. cnf.
In [16]: shutil.copy('/etc/my.cnf','/root/mysql/mysql.cnf')Out[16]: '/root/mysql/mysql.cnf'In [17]: ll /root/mysql/total 8-rw-r--r--. 1 root 960 Apr 22 16:57 my.cnf-rw-r--r--. 1 root 960 Apr 22 17:00 mysql.cnf
Syntax format of shutil. copytree:
copytree(src, dst)
Purpose:
Copy the entire folder. Copy the src folder, including all its files and subfolders, to the dst folder in the path. Returns the string of a newly copied folder path.
Example:
In [20]: shutil.copytree('/etc/yum.repos.d','/root/repo.back')Out[20]: '/root/repo.back'In [21]: ll /root/drwxr-xr-x. 2 root 4096 Apr 23 2017 repo.back/drwxr-xr-x. 2 root 4096 Apr 23 2017 repo.bak/
Note: dst must be a directory that does not exist in the system. Otherwise, an error is returned:
In [20]: shutil.copytree('/etc/yum.repos.d','/root/repo.bak')
FileExistsError: [Errno 17] File exists: '/root/repo.bak'2. Move and rename files and folders
Shutil. move ()
Syntax format:
move(stc,dst)
Purpose:
Move the folder in the path stc to the path dst, and return the absolute path string in the new location.
Example:
Move a.txt in the/root/directory to the/root/test/directory.
In [26]: shutil.move('/root/a.txt','/root/test/')Out[26]: '/root/test/a.txt'In [27]: ll /root/testtotal 4-rw-r--r--. 1 root 6 Apr 22 17:30 a.txt
Note:
If dst points to a folder, the src file will be moved to dst and the original file name will be kept, provided that dst must be an existing directory in the system.
If a file with the same name already exists in the target file, it will be overwritten.
3. delete files and folders
In the OS module:
OS. remove (path) can delete an object
OS. rmdir (path) can delete an empty folder.
In the shutil module:
Shutil. rmtree (path) can delete a folder and all its contents.
Syntax format:
os.rmdir(path)shutil.rmtree(path)
Example:
1 In [34]: os.remove('/root/test/a.txt') 2 3 In [35]: ll /root/test/ 4 total 0 5 6 In [36]: shutil.move('/root/CentOS-Base.repo','/root/test/') 7 Out[36]: '/root/test/CentOS-Base.repo' 8 9 In [37]: ll test10 total 411 -rw-r--r--. 1 root 2573 Apr 23 2017 CentOS-Base.repo12 13 In [38]: shutil.rmtree('/root/test')14 15 In [39]: ll16 total 1217 -rw-------. 1 root 1468 Apr 16 21:03 anaconda-ks.cfg18 drwxr-xr-x. 2 root 57 Apr 23 2017 download/19 drwxr-xr-x. 2 root 37 Apr 22 17:00 mysql/20 drwxr-xr-x. 6 root 95 Apr 16 21:58 py34/21 drwxr-xr-x. 3 root 18 Apr 16 23:01 python/22 drwxr-xr-x. 2 root 4096 Apr 23 2017 repo.back/23 drwxr-xr-x. 2 root 4096 Apr 23 2017 repo.bak/
Note:
All the preceding deletions are permanently deleted. For security, it is best to use the send2trash third-party module, which puts the deleted files into the recycle bin. This module has been integrated in python3.
Send2trash usage:
import send2trashsend2trash(path)
Ii. traverse the directory tree
For file processing, especially batch operations, You have to traverse directories. In python, the OS. walk () function in the OS module can be used.
This function recursively traverses the specified directory and sub-directory, and returns a 3-tuple message: the current directory name, sub-directory name, file name, excluding... and ..
Common usage:
#!/usr/bin/env python3.4#coding:utf-8import osfor foldName,subfolders,filenames in os.walk('/root/'): print('The current folder is: ' + foldName) for subfolder in subfolders: print('subfolder of ' + foldName + ':' + subfolder) for filename in filenames: print('file inside ' + foldName + ':' + filename) print('')Iii. Answers to practical projects
1 #! /Usr/bin/env python3.4 2 # coding: UTF-8 3 import OS 4 import shutil 5 import send2trash 6 7 #9.8.1 8 # copy the specified format file to the specified directory, the program below will be under the/etc directory. copy the conf file to the/root/test/directory. 9 src = '/etc/'10 dst ='/root/test/'11 ftype = '. conf '12 count = 013 for filename in OS. listdir (src): 14 if filename. endswith (ftype): 15 shutil. copy (src + filename, dst) 16 count + = 117 print ('file '+ src + filename +' \ t is copied to ---> '+ dst +' directory ') 18 print ("all" + ftype + "files under this directory have been copied to" + dst + "directory ") 19 print ('copied '+ str (count) + 'files') 20 21 #9.8.222 # search for files larger than MB in the specified directory, print out and delete 23 # You can manually create an empty file of the specified size for test 24 # dd if =/dev/zero of1_hello.txt bs = 100 M count = 125 for foldname, subfolders, filenames in OS. walk (dst): 26 for files in filenames: 27 if OS. path. getsize (dst + files)/1024/1024> 100:28 print ('files larger than MB are: '+ files + ''+ str (OS. path. getsize (dst + files)/1024/1024) + 'mb') 29 send2trash. send2trash (dst + files)
9.8.3
Assume that the following files exist in the test folder. The files are numbered with numbers starting with spam, but the numbers are not consecutive missing and some do not contain numbers, we need to find a file that does not match the file name and rename it into a sequential number.
(py34) [root@master test]# lsspam002.txt spam004.txt spam006.txt spam008.txt spam999.txtspam003.txt spam005.txt spam007.txt spam011.txt spamkkdf.txt
The reference code is as follows:
1 #! /Usr/bin/env python3.4 2 # coding: UTF-8 3 import re 4 import OS 5 fdir = '/root/python/py-9/test/'6 fdir_list = OS. listdir (fdir) 7 fdir_count = len (fdir_list) 8 print (fdir_list) 9 print ('total % d files under this directory '% fdir_count) 10 f_pre = 'spam' 11 f_num = [] 12 f_end = '.txt '13 fs_list = [] 14 # Here we only assume that the number of files is 100 small. 15 for I in range (1, fdir_count + 1): 16 if I <10:17 f_name = f_pre + '00' + str (I) + f_end18 f_num.append ('00' + str (I) 19 fs_list.append (f_name) 20 else: 21 f_name = f_pre + '0' + str (I) + f_end22 f_num.append ('0' + str (I) 23 fs_list.append (f_name) 24 max_f_num = max (f_num) 25 print ('the maximum number of files in this directory should be: % s' % max_f_num) 26 print ('correct file name should be :') 27 print (fs_list) 28 29 # use regular expressions to search for existing numbered files in the directory and store the 30 re_num = '\ d {3}' 31 yf_num = re in the yf_num list. findall (f_pre + re_num + f_end ,''. join (fdir_list) 32 ra_num = re. findall (re_num ,''. join (fdir_list) 33 print ('the specified file in the directory already exists: \ n % s' % yf_num) 34 35 # fq_list: List of file names with missing numbers in the directory 36 # fx_list: list of files with names to be modified in the current directory 37 fq_list = [] 38 fx_list = [] 39 # locate missing number the file and put it in the list. 40 for a in fs_list: 41 if a not in yf_num: 42 fq_list.append (a) 43 print ('the missing file number is \ n % s' % fq_list) 44 45 # Find the numbered or invalid numbered files in the directory and put them in the list. 46 for f_rename in fdir_list: 47 if f_rename not in fs_list: 48 fx_list.append (f_rename) 49 print ('the file name to be modified is \ n % s' % fx_list) 50 51 # change the file name 52 for k in fq_list: 53 for v in fx_list: 54 OS. rename (fdir + v, fdir + k) 55 # update the list 56 fx_list.remove (v) 57 print every time a file name has been repaired ('change the name :') 58 OS. system ('LS ')
The running result is as follows:
(Py34) [root @ master test] # python .. /file_check.py comment ', 'spam002.txt', 'spam006.txt ', 'spam005.txt', 'spam003.txt ', 'spam007.txt', 'spam008.txt ', comment', 'spam999.txt ', 'spam011.txt '] There are 10 files in this directory. the maximum number of files in this directory should be: 010. The correct file name should be: 'spam001.txt', 'spam002.txt ', 'spam003.txt', 'spam004.txt ', serial number files in the ', interval', interval ', 'spam008.txt', 'spam009.txt ', 'spam010.txt'] Directory: interval ', 'spam002.txt', 'spam006.txt ', 'spam005.txt', interval ', parameter ', 'spam008.txt', 'spam999.txt ', 'spam011.txt'] the missing file numbers are: parameter ', 'spam009.txt', 'spam010.txt '] the file names to be modified include parameter', 'spam999.txt ', 'spam011.txt '] after the name is changed, the result is: spam001.txt spam003.txt spam005.txt spam007.txt spam009.txtspam002.txt spam004.txt spam006.txt spam008.txt
There is still a small problem to be solved, and a file is missing.