Python folders and file action instances

Source: Internet
Author: User
Tags file copy regular expression

Python folders and file action instances


Regular expression to clean up the folder


Import OS
Import Sys
Import re
Import Shutil


def cleanup (dir, Regrex, num):
If not os.path.exists (dir) and not Os.path.isdir (dir):
print ' path%s is not existed or are not a directory '%dir
return False

Subfolderdict = {}
For Subi in Os.listdir (dir):
SF = Os.path.join (Dir,subi)
If Os.path.isdir (SF) and not Re.match (Regrex, subi) = none:
Sftime = Os.path.getctime (SF)
Subfolderdict[sftime] = SF
Else
Continue

subfolders = Subfolderdict.keys ()
If Len (subfolders) = = 0:return true

Subfolders.sort (Reverse=true)
n = int (num)
If Len (subfolders) >= N:
subfolders = Subfolders[n:]
Else:return true

If Len (subfolders) = = 0:return true

For Sftime in subfolders:
SF = Subfolderdict[sftime]
#shutil. Rmtree (SF)
print '%s is removed '% SF

return True


def usage ():
Usage = ' n
Function:n
Clean up subfolders in (dir), as a result:n
Just keep the subfolders which are matched with (Regrex), n
And the number of the Subfoler cannot more then (NUM). n
Usage:n
Python%s dir Regrex numn
'%sys.argv[0]
Print usage


if __name__ = = ' __main__ ':
If Len (sys.argv) = = 4:
Cleanup (sys.argv[1],sys.argv[2],sys.argv[3])
Else
Usage ()

Python subst Delete folder


Code:

Import OS
Import Sys
Import Shutil
Import subprocess

def runcommand (cmd):
return Subprocess.call (CMD)

def substdriveforpath (drive, path):
Substcmd = "subst" + "" + Drive + "" + Path
Return RunCommand (Substcmd)

def unsubstdriveforpath (drive):
Unsubstcmd = "subst" + "" +drive + "" + "/d"
RunCommand (Unsubstcmd)

def autosubst (path):
result = False

Useddrive = ""
For drive in "ZYXWVUTSRQPONMLKJIHGFEDCBA":
Fulldrive = drive + ":"
ReturnCode = Substdriveforpath (Fulldrive,path)
if (ReturnCode = 0):
Useddrive = fulldrive
Break
if (Not useddrive = ""):
result = True

return result, useddrive

Def rmdirwithsubst (dir, subst = true):

  If not os.path.exists (dir) and not Os.path.isdir (dir):
        print ' Path%s is not existed or isn't directory '%dir
        return false
 
  If subst:
    parent, CurDir = Os.path.split (dir)
    Re, d = Autosubst ( Parent)
    if re = = false:
      print  ' subst failed '
 & nbsp;    return False
    dir = d + ' + CurDir
 
  Shutil.rmtree (dir
  Unsubstdriveforpath (d)
   
  return True
 
def usage ():
  Usage = '
  When the dirctory cannot is removed in which some files path are too LONG.N
  Usage:python %s Folder1 [Folder2 ...] N '%sys.argv[0]
  Print usage


if __name__ = = ' __main__ ':
If Len (SYS.ARGV) < 2:usage ()
For folder in Sys.argv[1:]:
Rmdirwithsubst (folder)


File copy

1. Configuration file (Mojo.ini)

[Main]
Skin_path=e:accentrix.srcsunridersrcwebdataskins
Mojo_templates=sunriderreplicator_skin_1,sunriderreplicator_skin_2,sunriderreplicator_skin_3, Sunriderreplicator_skin_4
File_path=layout.master,images1.png

[Target]
Path=z:dataskins

--Here's an explanation:

Configuration of [main] source path

Skin_path: This is the directory location of the mojo skin.

Mojo_templates: The template directory is separated by commas to denote multiple, (in fact, other directories can be used)

File_path: The corresponding file under the template, separated by commas, can also contain subdirectories (eg:imagesimagek.jpg)

location to which [target] to copy

Path: Is the location of the mojo skin, refer to the Skin_path below the main node.

--Here's the code for py.

Import OS;
Import Configparser;
Import Shutil;
Def mojoupdate ():
Print "Application'll start to update"
Path= ". Mojo.ini"
main= "Main"
Config=configparser.configparser ();
Config.read (PATH)
Skinpath=config.get (Main, "Skin_path")

For _templatedirectory in Config.get (Main, "Mojo_templates"). Split (","):
sourcefolderpath=skinpath+ "" +_templatedirectory
For _file in Config.get (Main, "File_path"). Split (","):
Dest_path=config.get ("target", "path") + "" +_templatedirectory
dest=dest_path+ "" +_file
fullpath=sourcefolderpath+ "" +_file
Print FullPath
If Os.path.exists (FullPath):
Print "Copy file" +fullpath+ "to" + dest
CreateFolder (Os.path.split (dest) [0])
Shutil.copyfile (Fullpath,dest)
Else
Print FullPath + "is NOT exists"
Print "Copy Completed"
#-----------------------------------------------------

#recursion Create Folder
def createfolder (path):
If os.path.exists (path) ==false:
CreateFolder (Os.path.split (path) [0])
Os.mkdir (PATH)

-------------------------

Run the Mojoupdate () method to

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.