程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 更多關於編程 >> Python文件及目錄操作實例詳解

Python文件及目錄操作實例詳解

編輯:更多關於編程

       本文實例講述了Python文件及目錄操作的方法。分享給大家供大家參考。具體分析如下:

      在python中對文件及目錄的操作一般涉及多os模塊,os.path模塊。具體函數以及使用方法在程序中說明。

      ?

    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 62 63 64 65 66 #!/usr/bin/env python #-*- coding=UTF8 -*- import os import os.path as op def change_dir(): ''' 該函數顯示及改變前目錄 using chdir() to change current dir getcwd() can show the current working directory ''' directory="/tmp" #使用getcwd()返回當前目錄 print os.getcwd() #chdir改變當前目錄為:directory目錄 os.chdir(directory) print os.getcwd() def show_filesOfdir(whichDir): ''' 此函數只顯示目錄下的所有文件 using listdir() to shows all of the file execpt directory join() function catenate 'whichDir' with listdir() returns values isfile() check that file is a regular file ''' #listdir() 函數顯示前目錄的內容 for file in os.listdir(whichDir): #利用join()把whichDir目錄及listdir() 返回值連接起來組成合法路徑 file_name = op.join(whichDir,file) #isfile()函數可以判斷該路徑上的文件是否為一個普通文件 if op.isfile(file_name): print file_name def printaccess(path): ''' 顯示文件的最後訪問時間,修改時間 shows 'path' the last access time getatime() return the time of last access of path stat() return information of a file,use its st_atime return the time of last access ctime() return a string of local time ''' import time #利用ctime()函數返回最後訪問時間 #getatime()函數返回最後訪問時間,不過是以秒為單位(從新紀元起計算) print time.ctime(op.getatime(path)) #stat()函數返回一個對象包含文件的信息 stat = os.stat(path) #st_atime 最後一次訪問的時間 print time.ctime(stat.st_atime) print the modify time print "modify time is:", print time.ctime(op.getctime(path)) print "modify time is:", #st_ctime 最後一次修改的時間 print time.ctime(stat.st_ctime) def isDIR(path): ''' 一個os.path.isdir()函數的實現 Implement isdir() function 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')

      希望本文所述對大家的Python程序設計有所幫助。

    1. 上一頁:
    2. 下一頁:
    Copyright © 程式師世界 All Rights Reserved