#Encoding=utf8ImportOSImportShutil"""Directory Operations"""#get current working directory#print os.getcwd ()#Create a directory (only a single-level directory)#Os.mkdir (".. /yu ")#Renaming a directory#os.rename (".. /yu ",". /yu2 ")#Delete directory (only empty directories can be deleted)#Os.rmdir (".. /yu2 ")#Delete directories (empty directories and directories with content can be deleted)#Shutil.rmtree (".. /yu2 ")#Copy directory (YU3 directory must not exist)#Shutil.copytree (".. /yu2 ",". /yu3 ")#detects if a path is a directory#Os.path.isdir (".. /yu2 ")#Create a multilevel catalog#os.makedirs (R ' ... /yu4/123 ')"""file Operations"""#Create an empty file#fp = open (".. /yu4/test2.txt ", ' W ') #直接打开一个文件, does not exist then creates the file#Delete a file#Os.remove (".. /yu4/test2.txt ")#detects if the given path is a file#os.path.isfile (".. /yu4/test2.txt ")#returns the directory name and file name of a path#os.path.split (".. /yu4/test2.txt ")#returns the directory name of a path#os.path.dirname (".. /yu4/test2.txt ")#returns the file name of a path#os.path.basename (".. /yu4/test2.txt ")#Get File Size#os.path.getsize (".. /yu4/test2.txt ")"""File Content Operations"""#Open a file#fp = open ("Test.txt", ' W ') about open common mode W: Opened in write mode, a: Open in Append mode, r+: Open in read-write mode, w+: Open in read-write mode, A +: Open in read- write mode#fp.read ([size]) size is the length of the read#fp.readline ([size]) reads a row, if a size is defined, it is possible to return a part of a row#fp.readlines ([size]) takes each line of the file as a member and returns a list, if provided with a size indicating the total length of the read, that is, it may read only part of the file#Fp.write (str) writes STR to the file, write () does not append a newline character after Str#fp.writelines (SEQ) writes the contents of the SEQ to the file (multiline write-once). This function simply writes faithfully and does not add anything behind each line. #Fp.close () closes the file. #Fp.flush () writes the contents of the buffer to the hard disk#Fp.next () returns to the next line and shifts the file action marker to the next line. When a file is used for a statement such as for ... in file, it is called the next () function to implement the traversal.
Python file directory operations common methods Summary