python檔案夾遍曆,檔案操作,擷取檔案修改建立時間

來源:互聯網
上載者:User

標籤:list   tle   detail   []   copyto   tool   import   檔案夾   os.path   

在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.getmtime(name) #擷取檔案的修改時間 

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

os.stat(path).st_ctime #擷取檔案修改時間

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

 

列出檔案夾下修改時間的代碼如下:

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

python檔案夾遍曆,檔案操作,擷取檔案修改建立時間

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.