首页 > 编程 > Python > 正文

Python对文件和目录进行操作的方法(file对象/os/os.path/shutil 模块

2020-02-16 01:29:40
字体:
来源:转载
供稿:网友

使用Python过程中,经常需要对文件和目录进行操作。所有file类/os/os.path/shutil模块时每个Python程序员必须学习的。

下面通过两段code来对其进行学习。

1. 学习 file对象

2. 学习os/os.path/shutil模块

1.file对象学习:

项目中需要从文件中读取配置参数,python可以从Json,xml等文件中读取数据,然后转换成Python的内容数据结构。

下面以Json文件为例,实现从Json文件中获取配置参数。

code运行环境: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模块

在任何一个稍微大一点的项目中,少不了的需要对目录进行各种操作,

比如创建目录,删除目录,目录的合并等各种有关目录的操作。

下面以一段code为例,来实现对os/os.path/shutil模块的学习。

下面的code实现的是删除文件夹installation内的所有文件(里面有文件和文件夹),

注意:是删除文件夹installation里面所有的文件,并不删除installation这个文件夹。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表