使用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 lin