使用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è)文件夾。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注