The examples in this article describe the Python file and directory operations methods. Share to everyone for your reference. The specific analysis is as follows:
The operation of files and directories in Python typically involves multiple OS modules, Os.path modules. Specific functions and how they are used are described in the program.
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 The |
#!/usr/bin/env python #-*-coding=utf8-*-import os import Os.path As Op def change_dir (): "The function displays and changes the previous directory using ChDir () to the Change current dir getcwd () can show the current working Directo Ry ' directory= '/tmp #使用getcwd () returns the current directory print OS.GETCWD () #chdir改变当前目录为: Directory directory os.chdir (directory) print OS.GETCWD () def show_filesofdir (Whichdir): "This function only shows all files under the directory using Listdir () to shows all of the file execpt directory Jo In () function catenate ' Whichdir ' and Listdir () returns values Isfile () Check that the file is a regular file ' #listdir () The function displays the contents of the previous directory for file in Os.listdir (whichdir): #利用join () joins the Whichdir directory and the Listdir () return value to form a legal path file_name = Op.join (Whichdir, File) #isfile () function to determine whether the files on the path are a normal file If Op.isfile (file_name): print file_name def printaccess (path): ' Displays the last accessed time of the file, the modified time shows ' path ' to the end of access times GE Tatime () Return to the time of last access to Path stat () return information of a file,use it st_atime return the time of LA St Access CTime () return a string "Import Time" #利用ctime () function returns the last access #getatime () function returns the last access time, but in seconds (from the New Age The Print time.ctime (op.getatime (path)) #stat () function returns an object containing information stat = os.stat (path) #st_atime last accessed time print time.ctime ( Stat.st_atime) Print the Modify time print "Modify", Print Time.ctime (op.getctime (path)) print "Modify time is:", #st_ctime Last Modified time print Time.ctime (stat.st_ctime) def isdir (path): ' Implementation of a os.path.isdir () function implement Isdir () functi On by myself ' "Import stat MODE = Os.stat (path). St_mode #返回真假值 return Stat. S_isdir (MODE) if __name__== "__main__": Change_dir () show_filesofdir ('/root ') printaccess ('/etc/passwd ') print Isdir ('/etc ') |
I hope this article will help you with your Python programming.