Article From:

1) Folder

os.listdir()    #Display all the files under the folderAccess to the current working directory by os.getcwd ()Os.chdir ()Os.mkdir ()Os.path.exists ()Circuit breakage does not existOs.path.isdir () judgment is not a directoryThe combination path of os.path.join ()

2) Relative path and absolute path

One point: current directory, special name, not real folder.Two points: parent directoryOs.path.abspath ('.') display absolute pathIs os.path.isabs () interpretation of absolute path?OS.path.relpath () display relative path

3)Naming management

#Path names at all levelsOs.path.sep path segmentationGetting the name of the file by os.path.basename ()Getting the path name of os.path.dirname ()Os.path.split (path) partition path and file name'C:\\Users\\sothi\\Desktop\\py2018'('02-auto')Os.path.splitexT (path) segmentation to get the suffixExampleOs.path.split (r'C:\Users\sothi\Desktop\py2018\02-auto\test\1.pdf')('C:\\Users\\sothi\\Desktop\\py2018\\02-auto\\test','1.pdf')Os.path.splitext (r'C:\Users\sothi\Desktop\py2018\02-auto\test\1.pdf')('C:\\Users\\sothi\\Desktop\\py2018\\02-auto\\test\\1'','.pdf')

4) Delete files: operation risk, delete should be cautious


import shutil

#Copy / move: shutilShutil.copytree ('../test','../backup')Shutil.move ('007','009')

5) Just want the file format I want

- The properties of the fileOs.path.getsize file sizeOs.path.isfile () judgment is not a documentOs.stat file information: rightLimit, size, time of creation, etcOs.walk ()BeFor root, dirs, files in os.walk ('.'):Print (root, DIR)S, files)- suffix nameSplit cutting through split cuttingThe [-3:] suffix is usually 3 lengths:.TXTRegular matching by reThe endswith string matches the string by endswith.ExampleOs.walkTraversing directory, find the corresponding suffix name and size smaller than 1M file.Re_filename = re.compile ("(.*pdf$)" (.*docx$) "(.*xls$)")For root,Dirs, files in os.walk ('.'):Print (root, dirs, files)For name in files:File = os.path.join (root, name) file name under the root directoryIf re_filename.match (file) and os.path.getsiZe (file) < 1024*1024:Print (name)

Leave a Reply

Your email address will not be published. Required fields are marked *