OS modules are commonly used in development, and here are some common operations for OS modules, with code backup:
defosopt ():Try: #Delete the specified fileOs.remove ('D:\\selfwork\\python\\testdir\\file1.txt') except: Print('failed to delete the specified file! ') Try: #Renaming a specified fileOs.rename ('D:\\selfwork\\python\\testdir\\renamefile1.txt','D:\\selfwork\\python\\testdir\\renamefile2.txt') except: Print('Renaming the specified file failed! ') #generate all file names under the directory tree forRoot,dir,filesinchOs.walk ('D:\\selfwork\\python\\testdir', topdown=False):Print(Root)Print(dir)Print(Files) os.chdir ('D:\\selfwork\\python\\testdir')#Change the work path Print(Os.listdir ('D:\\selfwork\\python\\testdir'))#list files for the specified directory Print(OS.GETCWD ())#get the current work pathOs.chmod ('D:\\selfwork\\python\\testdir', Stat. File_attribute_readonly)Print(Os.path.basename ('D:\\selfwork\\python\\testdir\\renamefile2.txt'))#Remove directory path, return file name Print(Os.path.dirname ('D:\\selfwork\\python\\testdir\\renamefile2.txt'))#Remove file name, return directory path Print(Os.path.join ('d:\\','selfwork','Josin.txt'))#return to the tiled directory (D:\selfwork\josin.txt) Print(Os.path.split ('D:\\selfwork\\python\\testdir\\renamefile2.txt'))#Returns (DirName (), basename ()) tuples Print(Os.path.splitext ('D:\\selfwork\\python\\testdir\\renamefile2.txt'))#returns the (filename, extension) tuple Print(Time.localtime (Os.path.getatime ('D:\\selfwork\\python\\testdir\\renamefile2.txt')))#return last access time Print(Time.localtime (Os.path.getctime ('D:\\selfwork\\python\\testdir\\renamefile2.txt')))#Return creation Time Print(Time.localtime (Os.path.getmtime ('D:\\selfwork\\python\\testdir\\renamefile2.txt')))#Return modification Time Print(Os.path.getsize ('D:\\selfwork\\python\\testdir\\renamefile2.txt'))#return file size (bytes) Print(Os.path.exists ('d:\\selfwork\\python\\testdir\\'))#whether there is Print(Os.path.exists ('D:\\selfwork\\python\\testdir\\renamefile2.txt'))#whether there is Print(Os.path.isabs ('D:\\selfwork\\python\\testdir\\renamefile2.txt'))#is an absolute path Print(Os.path.isdir ('D:\\selfwork\\python\\testdir\\renamefile2.txt'))#is a directory Print(Os.path.isfile ('D:\\selfwork\\python\\testdir\\renamefile2.txt'))#is a file
Python-some general operational applications for OS modules