1. 程式人生 > >關於os模組中的資料夾遍歷,檔案操作,檔案的建立和修改時間的用法

關於os模組中的資料夾遍歷,檔案操作,檔案的建立和修改時間的用法

在Python中,檔案操作主要來自os模組,主要方法如下:

os.listdir(dirname):列出dirname下的目錄和檔案
os.getcwd():獲得當前工作目錄
os.curdir:返回當前目錄('.')
os.chdir(dirname):改變工作目錄到dirname

os.path.isdir(name):判斷name是不是一個目錄,name不是目錄就返回false
os.path.isfile(name):判斷name是不是一個檔案,不存在name也返回false
os.path.exists(name):判斷是否存在檔案或目錄name
os.path.getsize(name):獲得檔案大小,如果name是目錄返回0L

os.path.abspath(name):獲得絕對路徑
os.path.normpath(path):規範path字串形式
os.path.split(name):分割檔名與目錄(事實上,如果你完全使用目錄,它也會將最後一個目錄作為檔名而分離,同時它不會判斷檔案或目錄是否存在)
os.path.splitext():分離檔名與副檔名
os.path.join(path,name):連線目錄與檔名或目錄
os.path.basename(path):返回檔名
os.path.dirname(path):返回檔案路徑

os.remove(dir) #dir為要刪除的資料夾或者檔案路徑
os.rmdir(path) #path要刪除的目錄的路徑。需要說明的是,使用os.rmdir刪除的目錄必須為空目錄,否則函數出錯。

os.path.getctime(name) 獲取檔案的建立時間

os.path.getmtime(name) #獲取檔案的修改時間 

os.stat(path).st_mtime 獲取檔案的修改時間

os.stat(path).st_ctime 獲取檔案建立時間


使用os.stat的返回值statinfo的三個屬性獲取檔案的建立時間等
st_atime (訪問時間), st_mtime (修改時間), st_ctime(建立時間),例如,取得檔案修改時間:
>>> statinfo.st_mtime
1201865413.8952832
這個時間是一個linux時間戳,需要轉換一下
使用time模組中的localtime函式可以知道:
>>> import time
>>> time.localtime(statinfo.st_ctime)
(2008, 2, 1, 19, 30, 13, 4, 32, 0)
2008年2月1日的19時30分13秒(2008-2-1 19:30:13)

列出資料夾下修改時間的程式碼如下:

  1. #! /usr/bin/env python
  2. # coding:utf-8
  3. import os,datetime  
  4. base_dir = 'c:/'
  5. list = os.listdir(base_dir)  
  6. filelist = []  
  7. for i in range(0, len(list)):  
  8.     path = os.path.join(base_dir,list[i])  
  9.     if os.path.isfile(path):  
  10.         filelist.append(list[i])  
  11. for i in range(0, len(filelist)):  
  12.     path = os.path.join(base_dir, filelist[i])  
  13.     if os.path.isdir(path):  
  14.         continue
  15.     timestamp = os.path.getmtime(path)  
  16.     print timestamp  
  17.     ts1 = os.stat(path).st_mtime  
  18.     print ts1  
  19.     date = datetime.datetime.fromtimestamp(timestamp)  
  1.     print list[i],' 最近修改時間是: ',date.strftime('%Y-%m-%d %H:%M:%S')

沒事 的時候可以經常看看