Python string and file operations Common function analysis

Source: Internet
Author: User
Tags throw exception
This article analyzes the Python string and file operations commonly used functions. Share to everyone for your reference. Specific as follows:

#-*-Coding:utf-8-*-' Created on 2010-12-27@author:sumory ' ' Import itertoolsdef a_containsanyof_b (seq,aset): ' Judgment s Whether the EQ contains one or more items in the Aset seq can be a string or list aset should be a string or list "for item in Itertools.ifilter (ASET.__CONTAINS__,SEQ): retur N True return falsedef A_allin_b (seq,aset): "' Determines whether all items in the SEQ are in aset seq can be a string or the list aset should be a string or list ' for item in SE ' Q:IF Item not in Aset:return False return truedef a_containsall_b (seq,aset): "' Determine if SEQ contains all items in Aset seq can be a character The string or list aset should be either strings or a list of any set objects a,a.difference (b) is equivalent to A-set (b), which returns all elements in a that are not part of B ' return not set (Aset). Difference (s EQ) Import string# generates a reusable string of all characters Sumory_allchars=string.maketrans ("', ') def makefilter (keep):" ' Returns a function,    This function takes a source string as a parameter \ and returns a partial copy of the string \ This copy only includes characters in Keep, keep must be a normal string \ Call Example: Makefilter (' ABCA ') (' abcdefgh ijkal CBA ') \ Keep the preceding character in the string that follows the ABC a CBA "#按照sumory_allchars规则剔除sumory_allchars字符串中的keep里的字符 #这里得到keep在sumory_allchars的补集 Dele Techars=sumory_allchars.translate (Sumory_alLchars,keep) #生成并返回需要的过滤函数 (as closure) def Realdelete (SOURSESTR): Return Soursestr.translate (Sumory_allchars,deletechars)      return realdeletedef List_removesame (list): "Delete duplicates in list" ' templist=["for C in List:if C is not templist: Templist.append (c) return templistdef re_indent (str,numberofspace): ' Indent \ Divide string str by line break and add numberofspace space before each sentence \ re-combined into string ' ' ' spaces=numberofspace* ' ' Lines=[spaces+line.strip () for line in Str.splitlines ()] return ' \ n '. Join (lines) def replace_strby_dict (soursestr,dict,marker= ' "', Safe=false): ' Use a dictionary to replace the corresponding value of the marker package in the source string #如果safe为True, If the key is not found in the dictionary, do not replace if Safe:def lookup (W): Return Dict.get (W,w.join (marker*2)) #w. Join (MARKER*2) with marker package W #如果saf   If E is false, throw exception when key is not found in the dictionary \ #若将dict [w] to Dict.get (W) to return none Else:def lookup (W): Return dict[w] #根据marker切分源字符串 Splitparts=soursestr.split (marker) #取出切分后的奇数项 #因为切分后, the item in the source string in the list marker the parcel must be in the base part #就算是 the string "First" s is one "#分割后 The No. 0 item is an empty string, and the 1th item is first Splitparts[1::2]=map(Lookup,splitparts[1::2]) return ". Join (SplitParts) def simply_replace_strby_dict (soursestr,dict,safe=true):" Replace the substring of the $ tag in soursestr original string with dict content \ dict= {' name ': ' sumory ', ' Else ': ' Default '} $$5, $ $else, default ${name} ' s me Thod, Sumory ' s method ' style=string.     Template (SOURSESTR) #如果safe, can not be found in the dict will not replace, so keep the original string if Safe:return Style.safe_substitute (dict) #false, can not find to throw exception else: Return Style.substitute (dict) ################################################# #def Scanner (object,linehandler): "  Use the Linehandler method to traverse every item of the object "for lines in Object:linehandler" (line) def printfilelines (path): "reads the file screen of the path path to print" Fileobject=open (path, ' R ') #open不用放到try里 Try:for line in Fileobject:print (Line.rstrip (' \ n ')) finally:fileob    Ject.close () def writelisttofile (path,ilist): Fileobject=open (Path, ' W ') Try:fileobject.writelines (IList) Finally: Fileobject.close () Import zipfiledef listzipfilesinfo (path): Z=zipfile. ZipFile (path, ' R ') try:for FilenamE in Z.namelist (): bytes=z.read (filename) print (' file:%s size:%s '% (Unicode (filename, ' cp936 '). Decode (' utf-8 '), le N (bytes))) Finally:z.close () Import os,fnmatchdef list_all_files (root,patterns= ' * ', single_level=false,yield_  Folders=false): "List directory (or files under its subdirectories)" #分割模式到列表 patterns=patterns.split (';') For path,subdirs,files in Os.walk (root): if Yield_folders:files.extend (subdirs) Files.sort () for name in fi Les:for Pat in Patterns:if Fnmatch.fnmatch (name, Pat): Yield '/'. Join (Unicode (Os.path.join (Path,nam e), ' cp936 '). Split (' \ \ ')) Break if Single_level:breakdef swapextensions (root,before,after): If before[:1 ]!= '. ': before= '. ' +before Extensionlen=-len (before) if after[:1]!= '. ': after= '. ' +after for path,subdirs,files in Os.walk (root): For oldfile in Files:if oldfile[extensionlen:]==before:o Ldfile=os.path.join (path,oldfile) newfile=oldfile[:extensionlen]+after os.rename (Oldfile, newFile 

Hopefully this article will help you with Python programming.

  • 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.