亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Python對文件和目錄進行操作的方法(file對象/os/os.path/shutil 模塊)

 更新時間:2017年05月08日 09:00:48   投稿:jingxian  
下面小編就為大家?guī)硪黄狿ython對文件和目錄進行操作的方法(file對象/os/os.path/shutil 模塊)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

使用Python過程中,經常需要對文件和目錄進行操作。所有file類/os/os.path/shutil模塊時每個Python程序員必須學習的。

下面通過兩段code來對其進行學習。

1. 學習 file對象

2. 學習os/os.path/shutil模塊

1.file對象學習:

項目中需要從文件中讀取配置參數(shù),python可以從Json,xml等文件中讀取數(shù)據,然后轉換成Python的內容數(shù)據結構。

下面以Json文件為例,實現(xiàn)從Json文件中獲取配置參數(shù)。

code運行環(huán)境:python27+eclipse+pydev
Json文件名字:config_file.json
Json文件path:C:\temp\config_file.json

Json文件中的內容:

{"user":"Tom","username":"root_tom","password":"Jerryispig","ipaddr":"10.168.79.172"}
{"user":"Jerry","username":"root_jerry","password":"Tomispig","ipaddr":"10.168.79.173"}

代碼如下:

import json #use json file ,you must import json.  
  
def verify_file_class():  
  file_json=open(r'C:\temp\config_file.json','r') # open config_file.json file with 'r'  
  for each_line in file_json.readlines():     #read each line data  
    print each_line               # verify each line data by print each line data  
    
    each_line_dict = json.loads(each_line)    # each row of the data into the 'dict'type of python  
      
    print 'the type of the each_line_dict:{type}'.format(type=type(each_line_dict)) # verify whether is‘dict'type  
      
    print 'user is: {user}'.format(user=each_line_dict['user'])  
    print 'username is: {username}'.format(username=each_line_dict['username'])  
    print 'password is: {password}'.format(password=each_line_dict['password'])  
    print 'ipaddr is: {ipaddr} \n'.format(ipaddr=each_line_dict['ipaddr'])  
      
    #use username,password, ipaddr ( enjoy your programming ! )  
    
  file_json.close()  # don't forgot to close your open file before.  
  
if __name__ == '__main__':  
  verify_file_class() 

運行結果:

{"user":"Tom","username":"root_tom","password":"Jerryispig","ipaddr":"10.168.79.172"}  
the type of the each_line_dict:<type 'dict'>  
user is: Tom  
username is: root_tom  
password is: Jerryispig  
ipaddr is: 10.168.79.172   
  
{"user":"Jerry","username":"root_jerry","password":"Tomispig","ipaddr":"10.168.79.173"}  
the type of the each_line_dict:<type 'dict'>  
user is: Jerry  
username is: root_jerry  
password is: Tomispig  
ipaddr is: 10.168.79.173 

學習os/os.path/shutil模塊

在任何一個稍微大一點的項目中,少不了的需要對目錄進行各種操作,

比如創(chuàng)建目錄,刪除目錄,目錄的合并等各種有關目錄的操作。

下面以一段code為例,來實現(xiàn)對os/os.path/shutil模塊的學習。

下面的code實現(xiàn)的是刪除文件夾installation內的所有文件(里面有文件和文件夾),

注意:是刪除文件夾installation里面所有的文件,并不刪除installation這個文件夾。

代碼如下:

code運行環(huán)境:python27+eclipse+pydev

import os 
import shutil  
 
 
def empty_folder(dir): 
  try: 
    for each in os.listdir(dir): 
      path = os.path.join(dir,each) 
      if os.path.isfile(path): 
        os.remove(path) 
      elif os.path.isdir(path): 
        shutil.rmtree(path) 
    return 0 
  except Exception as e: 
    return 1 
 
 
if __name__ == '__main__': 
  dir_path=r'D:\installation' 
  empty_folder(dir_path) 

上面短短的幾行代碼,就包含了6個與os/os.path/shutil模塊相關的API。分別是:

1. os.listdir(dir) 
2. os.path.join(dir, each) 
3. os.path.isfile(path) /os.path.isdir(path) 
4. os.remove(path) 
5. shutil.rmtree(path) 

下面分別對上面6個最常見的與目錄有關的API進行簡單的學習。

1. os.listdir(dir)

這個函數(shù)返回指定目錄下的所有文件和目錄名組成的一個列表。

就是說返回一個列表,這個列表里的元素是由指定目錄下的所有文件和目錄組成的。

>>> import os 
>>> os.listdir(r'c:\\') 
['$Recycle.Bin', 'Documents and Settings', 'eclipse', 'hiberfil.sys', 'inetpub', 'Intel', 'logon_log.txt', 'MSOCache', 'pagefile.sys', 'PerfLogs'<span style="font-family: Arial, Helvetica, sans-serif;">]</span> 

2. os.path.join(dir, each)

連接目錄與文件名或目錄

>>> import os 
>>> os.path.join(r'c:\doog',r's.txt') 
'c:\\doog\\s.txt' 
>>> os.path.join(r'c:\doog',r'file') 
'c:\\doog\\file' 

3. os.path.isfile(path) / os.path.isdir(path)

os.path.isfile(path) 用于判斷path是否為文件,若是文件,返回True,否則返回False。

os.path.isdir(path) 用于判斷path是否為目錄,若是目錄,返回True,否則返回False。

>>> import os 
>>> filepath=r'C:\Program Files (x86)\Google\Chrome\Application\VisualElementsManifest.xml' 
>>> os.path.isdir(filepath) 
False 
>>> os.path.isfile(filepath) 
True 

4. os.remove(path)

刪除指定文件。無論文件是否是空,都可以刪除。

注意:這個函數(shù)只能刪除文件,不能刪除目錄,否則會報錯。

>>> import os 
>>> os.removedirs(r'c:\temp\david\book\python.txt') 

5. shutil.rmtree(path)

如果目錄中有文件和目錄,也就是說一個目錄中不管有多少子目錄,這些子目錄里面不管有多少目錄和文件。

我想刪除這個上層目錄(注意:是刪除這個目錄及其這個目錄中的所有文件和目錄)。

如何做呢?

就需要使用shutil模塊中的rmtree()函數(shù)。

>>> import shutil 
>>> shutil.rmtree(r'C:\no1') 

以上這篇Python對文件和目錄進行操作的方法(file對象/os/os.path/shutil 模塊)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

  • python定時任務sched庫用法簡單實例

    python定時任務sched庫用法簡單實例

    sched可用于定時任務,唯一需要注意的就是,這些任務在一個線程中運行,如果前面的任務耗時過長,則后面的任務將順延執(zhí)行,下面這篇文章主要給大家介紹了關于python定時任務sched庫用法的相關資料,需要的朋友可以參考下
    2023-01-01
  • Django靜態(tài)資源部署404問題解決方案

    Django靜態(tài)資源部署404問題解決方案

    這篇文章主要介紹了Django靜態(tài)資源部署404問題解決方案,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-05-05
  • Pycharm 設置默認頭的圖文教程

    Pycharm 設置默認頭的圖文教程

    今天小編就為大家分享一篇Pycharm 設置默認頭的圖文教程,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-01-01
  • 深度學習TextRNN的tensorflow1.14實現(xiàn)示例

    深度學習TextRNN的tensorflow1.14實現(xiàn)示例

    這篇文章主要介紹了深度學習TextRNN的tensorflow1.14實現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-01-01
  • python Matplotlib數(shù)據可視化(1):簡單入門

    python Matplotlib數(shù)據可視化(1):簡單入門

    這篇文章主要介紹了python Matplotlib的相關資料,幫助大家入門matplotlib,繪制各種圖表,感興趣的朋友可以了解下
    2020-09-09
  • 詳解Python進行數(shù)據相關性分析的三種方式

    詳解Python進行數(shù)據相關性分析的三種方式

    相關系數(shù)量化數(shù)據集的變量或特征之間的關聯(lián)。這些統(tǒng)計數(shù)據對科學和技術非常重要,Python?有很好的工具可以用來計算它們。SciPy、NumPy?和Pandas相關方法以及數(shù)據可視化功能,感興趣的可以了解一下
    2022-04-04
  • 在Python中使用元類的教程

    在Python中使用元類的教程

    這篇文章主要介紹了在Python中使用元類的教程,是Python當中的基礎知識,代碼基于Python2.x版本,需要的朋友可以參考下
    2015-04-04
  • python實現(xiàn)爬山算法的思路詳解

    python實現(xiàn)爬山算法的思路詳解

    爬山算法會收斂到局部最優(yōu),解決辦法是初始值在定義域上隨機取亂數(shù)100次,總不可能100次都那么倒霉。這篇文章主要介紹了python實現(xiàn)爬山算法的思路詳解,需要的朋友可以參考下
    2019-04-04
  • python 爬取京東指定商品評論并進行情感分析

    python 爬取京東指定商品評論并進行情感分析

    本文主要講述了利用Python網絡爬蟲對指定京東商城中指定商品下的用戶評論進行爬取,對數(shù)據預處理操作后進行文本情感分析,感興趣的朋友可以了解下
    2021-05-05
  • Django中密碼的加密、驗密、解密操作

    Django中密碼的加密、驗密、解密操作

    這篇文章主要介紹了Django中密碼的加密、驗密、解密操作,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-12-12

最新評論