python对文本文档的读写和删除操作-1
2016-08-07 19:57
363 查看
项目需要,首先需要读取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
相关文章推荐
- python对文本文档的读写和删除操作-2
- Java文本文档的读写操作(复习笔记)
- Python文件操作,open读写文件,追加文本内容实例
- Python 文件/文件夹操作(读写read/write、复制copy、删除delete、重命名rename)
- Python读写文本文档详解
- C++ (IO操作小案列) 基于本地文本文档的读写
- Python文件操作,open读写文件,追加文本内容(转)
- Python文件操作,open读写文件,追加文本内容
- Python(18):对文件的操作(读写、创建、拷贝、移动、删除)
- 学习python对文本文档的操作
- python 文本读写操作
- 使用 ruamel.yaml 读写 yaml 文档 Python 操作笔记
- C#操作文本读写流--- StreamWritter and StreamReader
- 短信选名字操作(listbox读文本文档)
- asp.net读写添加修改删除操作xml文件 代码如下(C#)
- 如何完成.Net下XML文档的读写操作
- asp.net 对xml文件的读写,添加,修改,删除操作
- 文件系统管理 之 有关ext2文件系统下反删除(Undelete)操作恢复数据的文档
- ASP对XML文档中文本的增加、删除、修改、查看
- 创建可编辑的xml文档(之四) 删除、改名、插入操作