项目需要,首先需要读取json格式存储的文本文档,该文本文档存在指定的目录中,该目录下有很多的文本文档,需要在文本文档中找到里面的calls数据,然后把calls数据返回,供robotframework 调用
#-*-coding:utf-8 -*-
import os
import glob
import datetime
import json
import types
class ReadTxt(object):
def __init__(self):
self._txt = None
self._current_dir_path = None
def get_current_directory_path(self, dirpath):
self._current_dir_path = dirpath
return self._current_dir_path
def get_txt_files(self,):
file_list = []
for fn in glob.glob(self._current_dir_path + os.sep + '*.txt'):
if os.path.isdir(fn):
self.get_txt_files(self._current_dir_path + os.sep + fn)
else:
print fn
time_str = datetime.datetime.fromtimestamp(os.path.getctime(fn))
print time_str
print os.path.getctime(fn)
file_list.append(fn)
print file_list
return file_list
def get_latest_file(self, file_list):
if len(file_list) > 0:
latest_file = file_list[0]
for file_index in file_list:
if(os.path.getctime(latest_file)<= os.path.getctime(file_index)):
latest_file = file_index
else:
latest_file = ''
return latest_file
def read_txt_file(self, filename):
if os.path.isfile(filename):
with open(filename) as a_file:
book_list = a_file.read().splitlines()
print book_list
txt_data = json.loads(book_list[0])
calls_num = txt_data["summary"]["calls"]
print calls_num
else:
calls_num = 'error'
return calls_num
def delete_txt_file(self,):
for infile in glob.glob(os.path.join(self._current_dir_path, '*.txt')):
print infile
os.remove(infile)
if __name__ == '__main__':
file_path_list = []
txt = ReadTxt()
current_dir = txt.get_current_directory_path("F:/neng fen study/python_files")
print current_dir
file_path_list = txt.get_txt_files()
print file_path_list
latest_file = txt.get_latest_file(file_path_list)
print 'latest_file:' + latest_file
calls_num = txt.read_txt_file(latest_file)
print calls_num
txt.delete_txt_file()
base_dir = os.path.dirname(current_dir)
print base_dir