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

Let's learn it through two pieces of code.

Learning the file object

2. Learn the os/os.path/shutil module

1.file object learning:

Configuration parameters need to be read from the file in the project,Python can read data from json, xml and other files,Then convert it into python's content data structure.

Take the json file as an example,To achieve the configuration parameters from the json file.

Code running environment:python27 + eclipse + pydev

json file name:config_file.json

json file path:c:\ temp \ config_file.json

Content in json file:

{"user":"tom", "username":"root_tom", "password":"jerryispig", "ipaddr":""}

{"user":"jerry", "username":"root_jerry", "password":"tomispig", "ipaddr":""}

code show as below:

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__":
  verify_file_class ()

operation result:

{"user":"tom", "username":"root_tom", "password":"jerryispig", "ipaddr":""}
the type of the each_line_dict:<type "dict">
user is:tom
username is:root_tom
password is:jerryispig
ipaddr is:
{"user":"jerry", "username":"root_jerry", "password":"tomispig", "ipaddr":""}
the type of the each_line_dict:<type "dict">
user is:jerry
username is:root_jerry
password is:tomispig
ipaddr is:

Learn the os/os.path/shutil module

In any slightly larger project,It is indispensable to perform various operations on the directory,

Like creating directories,Delete the directory,Directory merging and other operations related to directories.

Take a piece of code as an example to learn the os/os.path/shutil module.

The following code implements the deletion of all files in the folder installation (there are files and folders in it),

Note:It is to delete all files in the folder installation,It does not delete the installation folder.

code show as below:

Code running 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):
        os.remove (path)
      elif os.path.isdir (path):
        shutil.rmtree (path)
    return 0
  except exception as e:
    return 1
if __name__ == "__main__":
  dir_path=r "d:\ installation"
  empty_folder (dir_path)

Just a few lines of code above,It contains 6 APIs related to the os/os.path/shutil module. They are:

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)

The following is a simple study of the above 6 most common directory-related APIs.

1.os.listdir (dir)

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

That is to return a list,The elements in this list are all 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>]</span>

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

Link directories with file names or directories

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

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

os.path.isfile (path) is used to determine whether path is a file,For documents,Returns true, otherwise returns false.

os.path.isdir (path) is used to determine whether path is a directory,For directories,Returns true, otherwise returns 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)

Delete the specified file.Whether or not the file is empty,Can be deleted.

Note:This function can only delete files,Can't delete directory,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 the directory,In other words, no matter how many subdirectories are in a directory,No matter how many directories and files are in these subdirectories.

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

How to do it?

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

>>import shutil
>>shutil.rmtree (r "c:\ no1")
  • Previous AngularJs filter filter and custom filter example
  • Next Python implements SSH remote login and executes commands (share)