" "using adorners to read and write files" "#def check_permission (func):#"' demonstrates nested function definitions and uses ' '#def wrapper (*args,**kwargs):#"' *args: Receives any number of arguments and stores them in a tuple; **kwargs: Receive keyword parameter display assignment and deposit in dictionary"#if Kwargs.get (' username ')! = ' Admin ':#Raise Exception (' sorry,you is not allowed ')#return func (*args,**kwargs)#return wrapper##class Readwritefile (object):## Decorator#@check_permission #read = check_permission (read)#def read (self,username,filename):#return open (filename, ' r '). Read ()##def write (self,username,filename,content):#with open (filename, ' A + ') as OP: #采用with上下文管理语句#op.write (content)##open (filename, ' A + '). Write (content)## normal function Use#writes = Check_permission (write)##t = readwritefile ()#Print (T.read (username= ' admin ', filename=r ' C:\Users\PGIDYSQ\Desktop\1111111e.gen '))#Print ("*" *60)#t.write (' admin ', filename=r ' C:\Users\PGIDYSQ\Desktop\1111111e.gen ', content= ' add content ... ')#print ("-" *60)#With open (R ' C:\Users\PGIDYSQ\Desktop\1111111e.gen ') as FP:##print (List (map (len,fp.readlines )))#Print (List (Enumerate (Fp.readlines () )))## for line in fp:## Print (line)#Pickle UseImportPicklesrcurl=r'C:\Users\PGIDYSQ\Desktop\1111111e.gen'Dsturl=r'C:\Users\PGIDYSQ\Desktop\tset.bat'With open (srcurl,encoding='Utf-8') as Src,open (Dsturl,'WB') as Dest:lines=src.readlines () pickle.dump (Len (lines), dest)#Number of rows forLineinchLines:pickle.dump (Line,dest) with open (R'C:\Users\PGIDYSQ\Desktop\tset.bat','RB') as Fp:n= Pickle.load (FP)#Convert line number forIinchrange (n):#Print (Pickle.load (FP))BB =pickle.load (FP)Print(BB)#struct Use#struct.pack,unpack== "Write (struct), read (9)" "traverse all subdirectories and files under the specified directory" "ImportOSdefVisitdir (path):if notOs.path.isdir (path):Print('Error') return forListsinchOs.listdir (path): Sub_path=Os.path.join (path,lists)Print(Sub_path)ifOs.path.isdir (Sub_path): Visitdir (Sub_path)#Recursive invocation#Visitdir (R ' F:\UpSVNProject ')#Traverse using the Os.walk () methoddefVisitDir2 (path):if notOs.path.isdir (path):Print('Error') returnList_dirs=os.walk (path) forRoot,dirs,filesinchList_dirs: forDinchdirs:Print(Os.path.join (root,d)) forFinchFiles:Print(Os.path.join (root,f))#VisitDir2 (R ' F:\UpSVNProject ')
Python uses adorners to read and write files ' and traverse files directory