The examples in this article describe how Python files and directory operations work. Share to everyone for your reference. The specific analysis is as follows:
The operation of files and directories in Python generally involves multiple OS modules, Os.path modules. Specific functions and how to use them are described in the program.
#!/usr/bin/env python#-*-Coding=utf8-*-import osimport Os.path as Opdef change_dir (): "The function shows and changes before the directory using ChDir () to Change present dir getcwd () can show the current working directory "directory="/tmp "#使用getcwd () to return the currently directory print OS. GETCWD () #chdir改变当前目录为: Directory directory os.chdir (directory) print os.getcwd () def show_filesofdir (Whichdir): "This function shows only the directory All files using Listdir () to shows all of the file execpt directory join () function catenate ' Whichdir ' with Listdir () return s values isfile () Check that the file is a regular file ' ' #listdir () function displays the contents of the previous directory for the file in Os.listdir (whichdir): # Use Join () to concatenate the Whichdir directory and the Listdir () return value to form a legitimate path file_name = Op.join (whichdir,file) #isfile () function to determine if the file on that path is a normal file if op . Isfile (file_name): Print file_namedef printaccess (path): "Displays the last accessed time of the file, modified time shows ' path ', in Getatime () Return the time of last access to Path stat () return information of a file,use its st_atime return the TI Me of the last access CTime() return a string of local time ' import time #利用ctime () function returns the last access Times #getatime () function returns the last access times, but in seconds (calculated from the epoch) print T The Ime.ctime (path) #stat () function returns an object that contains the information for the file, stat = os.stat (path) #st_atime The time of the last visit, print time.ctime (stat.st_ Atime) Print the Modify time print "Modify time is:", print time.ctime (path) print "Op.getctime time is:", #s T_ctime Last Modified time print Time.ctime (stat.st_ctime) def isdir (path): implementation of a Os.path.isdir () function Implement isdir () functions 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 IsD IR (' etc ')
Hopefully this article will help you with Python programming.