One, create 1, create file open (path, ' W ') 2, create directory (1) os.mkdir (pt[, mode=0777]) New directory PT, the parameter mode indicates the permissions of the generated directory, which by default is super privilege, which is 0777. (2) Os.makedirs (PT) Create a multi-level directory such as creating \t1\t2\t33 in the Python directory, creating temporary Files Os.tmpfile () the "w+b" mode to create and open a temporary file. The cache is in memory and does not occupy memory space. No need to delete, close () does not exist after Fp=os.tmpfile () fp.write (' Fjwioe ') fp.seek (0) Print fp.read () fp.close () II, delete 1, Delete file Os.remove (' e:\\tmp\\01.txt ') delete a file deletes a specified file, the parameter filepath represents the path where the file is located. Note: This method can only delete files and cannot delete directories. 2, delete directory (1) os.rmdir () Delete single-level empty directory, if the directory is not empty can not be deleted, will error (2) os.removedirs (' e:\\python\\t1\\t2\\t3 ') Delete multi-level directory three, File and directory Copy and move import shutil copy or move a file, directory structure 1, shutil.copyfile (path1,path2) Copy the file path1 the contents of the file to copy to the file path2 2, Shutil.move ( PATH1,PATH2) move files, folders to move files path1 path2 under 3, shutil.copy (path1,path2) copy files, folders to copy files path1 to path2 4, Shutil.copytree ( PATH1,PATH2) Copy the entire directory structure copy the path1 directory to path2 5, Shutil.rmtree (SRC) recursively delete a directory and all contents within the directory Four, traverse files and directories 1, Os.walk (top, Topdown=true,oneerror=none,folowlinks=false) Top: root node Followlinks: Generally not topdown=true from top to bottom traversal oneerror: When there is no value, An error also continues to traverse the Traverse file and directory, returning the result is a meta-ancestor type for i,j,k in Os.walk (' d:\\tmp ') I: Returns the current directory root node J: All directories under current node K: All files under the current node are not worth the case, return []eg:for i,j,k in Os.walk (' d:\\tmp '):p rint iprint jprint k results: d:\tmp[][' test13.txt '] 2, Os.path.walk (top,func,arg) Python3 above do not support this traversal method, the use of Func (Arg,dirname,files) is not recommended: callback function Arg:os.path.walk () Argdirname: root directory Files: list, all files and folders def findfile (arg, dirname, files):p rint ' ***************************** ' Print Argprint dirnameprint filesos.path.walk (' e:\\tmp ', FindFile, ()) 3, Os.listdir (' e:\\tmp ') Lists all files and subdirectories under the specified directory, including hidden files or directories, and returns them as a list.
Python file operations: file, directory operations