python对文本文档的读写和删除操作-1

项目需要,首先需要读取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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值