国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > Python > 正文

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

2019-11-25 16:11:46
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

使用Python過(guò)程中,經(jīng)常需要對(duì)文件和目錄進(jìn)行操作。所有file類(lèi)/os/os.path/shutil模塊時(shí)每個(gè)Python程序員必須學(xué)習(xí)的。

下面通過(guò)兩段code來(lái)對(duì)其進(jìn)行學(xué)習(xí)。

1. 學(xué)習(xí) file對(duì)象

2. 學(xué)習(xí)os/os.path/shutil模塊

1.file對(duì)象學(xué)習(xí):

項(xiàng)目中需要從文件中讀取配置參數(shù),python可以從Json,xml等文件中讀取數(shù)據(jù),然后轉(zhuǎn)換成Python的內(nèi)容數(shù)據(jù)結(jié)構(gòu)。

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

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

Json文件中的內(nèi)容:

{"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() 

運(yùn)行結(jié)果:

{"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 

學(xué)習(xí)os/os.path/shutil模塊

在任何一個(gè)稍微大一點(diǎn)的項(xiàng)目中,少不了的需要對(duì)目錄進(jìn)行各種操作,

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

下面以一段code為例,來(lái)實(shí)現(xiàn)對(duì)os/os.path/shutil模塊的學(xué)習(xí)。

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

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

代碼如下:

code運(yùn)行環(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個(gè)與os/os.path/shutil模塊相關(guān)的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) 

下面分別對(duì)上面6個(gè)最常見(jiàn)的與目錄有關(guān)的API進(jìn)行簡(jiǎn)單的學(xué)習(xí)。

1. os.listdir(dir)

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

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

>>> 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)

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

注意:這個(gè)函數(shù)只能刪除文件,不能刪除目錄,否則會(huì)報(bào)錯(cuò)。

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

5. shutil.rmtree(path)

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

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

如何做呢?

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

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

以上這篇Python對(duì)文件和目錄進(jìn)行操作的方法(file對(duì)象/os/os.path/shutil 模塊)就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持武林網(wǎng)。

發(fā)表評(píng)論 共有條評(píng)論
用戶(hù)名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 旬阳县| 陈巴尔虎旗| 永丰县| 苍南县| 北海市| 南投县| 屏山县| 吉隆县| 乌兰县| 汽车| 孟村| 海口市| 乐东| 琼结县| 岑巩县| 武威市| 美姑县| 祁阳县| 吉林省| 瑞丽市| 康平县| 夏津县| 华池县| 海城市| 喀喇| 丹寨县| 康马县| 金川县| 久治县| 临澧县| 河南省| 枞阳县| 襄汾县| 敦煌市| 哈尔滨市| 固安县| 晋江市| 晴隆县| 三亚市| 武义县| 蓬莱市|