Python method of file object and os and os. path and shutil module

  • 2020-05-30 20:33:27
  • OfStack

With Python, you often need to manipulate files and directories. All file classes /os/ os.path /shutil modules must be learned by every Python programmer.

Here's a look at code in two paragraphs.

1. Learn file objects

2. Learning os/os. path/shutil modules

1.file object learning:

The project needs to read configuration parameters from files. python can read data from files such as Json and xml, and then convert them into the content data structure of Python.

Take the Json file as an example to obtain configuration parameters from the Json file.

code operating environment: python27+eclipse+pydev
Json file name: config_file.json
path: C:\temp\ config_file.json

Contents of Json file:


The code is as follows:

import json #use json file ,you must import json.  
def verify_file_class():  
  file_json=open(r'C:\temp\config_file.json','r') # open config_file.json file with 'r'  
  for each_line in file_json.readlines():     #read each line data  
    print each_line               # verify each line data by print each line data  
    each_line_dict = json.loads(each_line)    # each row of the data into the 'dict'type of python  
    print 'the type of the each_line_dict:{type}'.format(type=type(each_line_dict)) # verify whether is ' dict'type  
    print 'user is: {user}'.format(user=each_line_dict['user'])  
    print 'username is: {username}'.format(username=each_line_dict['username'])  
    print 'password is: {password}'.format(password=each_line_dict['password'])  
    print 'ipaddr is: {ipaddr} \n'.format(ipaddr=each_line_dict['ipaddr'])  
    #use username,password, ipaddr ( enjoy your programming ! )  
  file_json.close()  # don't forgot to close your open file before.  
if __name__ == '__main__':  

Operation results:

the type of the each_line_dict:<type 'dict'>  
user is: Tom  
username is: root_tom  
password is: Jerryispig  
ipaddr is:   
the type of the each_line_dict:<type 'dict'>  
user is: Jerry  
username is: root_jerry  
password is: Tomispig  
ipaddr is: 

Learning os/os path/shutil module

In any project that is slightly larger than 1, there is a need to perform various operations on the directory,

For example, create directory, delete directory, directory merge and other operations related to the directory.

Below 1 paragraph code, for example, to achieve os/os path/shutil module of learning.

What code below does is delete all files in the installation folder (which contains files and folders),

Note: delete all files in installation, not installation.

The code is as follows:

code operating environment: python27+eclipse+pydev

import os 
import shutil  
def empty_folder(dir): 
    for each in os.listdir(dir): 
      path = os.path.join(dir,each) 
      if os.path.isfile(path): 
      elif os.path.isdir(path): 
    return 0 
  except Exception as e: 
    return 1 
if __name__ == '__main__': 

Above a few lines of code, and contains six os/os path/shutil API related modules. Respectively is:

1. os.listdir(dir) 
2. os.path.join(dir, each) 
3. os.path.isfile(path) /os.path.isdir(path) 
4. os.remove(path) 
5. shutil.rmtree(path) 

Here's a quick look at each of the six most common directory related API.

1. os.listdir(dir)

This function returns a list of all files and directory names in the specified directory.

This returns a list of all the files and directories in the specified directory.

>>> import os 
>>> os.listdir(r'c:\\') 
['$Recycle.Bin', 'Documents and Settings', 'eclipse', 'hiberfil.sys', 'inetpub', 'Intel', 'logon_log.txt', 'MSOCache', 'pagefile.sys', 'PerfLogs'<span style="font-family: Arial, Helvetica, sans-serif;">]</span> 

2. os.path.join(dir, each)

Connect a directory to a file name or directory

>>> import os 
>>> os.path.join(r'c:\doog',r's.txt') 
>>> os.path.join(r'c:\doog',r'file') 

3. os.path.isfile(path) / os.path.isdir(path)

os.path.isfile (path) is used to determine whether path is a file. If it is a file, return True; otherwise, return False.

os.path.isdir (path) is used to determine whether path is a directory. If so, return True, otherwise return False.

>>> import os 
>>> filepath=r'C:\Program Files (x86)\Google\Chrome\Application\VisualElementsManifest.xml' 
>>> os.path.isdir(filepath) 
>>> os.path.isfile(filepath) 

4. os.remove(path)

Deletes the specified file. Whether the file is empty or not, it can be deleted.

Note: this function can only delete files, not directories, otherwise an error will be reported.

>>> import os 
>>> os.removedirs(r'c:\temp\david\book\python.txt') 

5. shutil.rmtree(path)

If there are files and directories in a directory, that means that no matter how many subdirectories there are in a directory, it doesn't matter how many directories and files there are in those subdirectories.

I want to delete this upper directory (note: delete this directory and all the files and directories in this directory).

How do you do that?

You need to use the rmtree() function in the shutil module.

>>> import shutil 
>>> shutil.rmtree(r'C:\no1') 

Related articles: