直接上源码
__author__ = 'man'
import os
import sys
import time
import json
import shutil
import configparser
class Man_File_handle():
'''
对文件操作的类;
@ file_path : 文件路径;
'''
def __init__(self, file_path):
self.file_path = file_path
def read_all_data(self):
if self.examine_file() == True:
file_all_data = []
with open( self.file_path, 'r', encoding='utf-8') as file:
for line in file:
file_all_data.append(line)
return file_all_data
else:
return self.examine_file()
def read_all_data_1(self):
file_all_data = []
with open( self.file_path, 'r', encoding='utf-8') as file:
for line in file:
file_all_data.append(line)
return file_all_data
def examine_file(self):
if os.path.exists(self.file_path) == False:
print("文件不存在")
return "NotFile"
else:
return True
def write_one_data(self,datas):
with open( self.file_path, 'a+', encoding='utf-8') as file:
print(type(datas))
input_data = str(datas)
print(type(input_data))
file.write(input_data+"\n")
def write_file_all(self,data_list):
with open( self.file_path, 'w+', encoding='utf-8') as file:
for file_data in data_list:
file.write(file_data)
def write_datas(self,datas):
with open( self.file_path, 'w+', encoding='utf-8') as file:
file.write(datas)
def add_data(self,datas):
with open( self.file_path, 'a+', encoding='utf-8') as file:
input_data = str(datas)
file.write(input_data+"\n")
def get_file_data_len(self):
file_all_datas = self.read_all_data()
if file_all_datas != 'NotFile':
print(len(file_all_datas))
return len(file_all_datas)
def get_file_line_data(self,len_number):
data_cont = 0
with open( self.file_path, 'r', encoding='utf-8') as file:
for line in file:
if(data_cont == (len_number-1)):
print(data_cont)
print(type(line))
return line
break
data_cont+=1
else:
print("not find file len Min = 1 ; Max = "+str(data_cont))
def modif_file_line_data(self,len_number,datas):
input_data = str(datas)
input_data = input_data.replace("\'","\"")
file_all_datas = self.read_all_data()
if file_all_datas != 'NotFile':
file_all_datas[(len_number-1)] = input_data+"\n"
with open( self.file_path, 'w+', encoding='utf-8') as file:
for file_data in file_all_datas:
file.write(file_data)
def add_file_line_data(self,len_number,datas):
input_data = str(datas)
input_data = input_data.replace("\'","\"")
file_all_datas = self.read_all_data()
if file_all_datas != 'NotFile':
file_all_datas.insert( (len_number-1), input_data+"\n")
self.write_file_all(file_all_datas)
def del_dile_line_data(self,len_number):
file_all_datas = self.read_all_data()
if file_all_datas != 'NotFile':
del file_all_datas[(len_number-1)]
self.write_file_all(file_all_datas)
def clear_empty(self):
file_all_datas = self.read_all_data()
if file_all_datas != 'NotFile':
file_all_datas = [x for x in file_all_datas if x != '\n' and x != '']
kongge = " "
kongge_number = 0
while kongge_number < 10:
str_pipei = kongge * kongge_number + "\n"
if str_pipei in file_all_datas:
file_all_datas.remove(str_pipei)
else:
kongge_number += 1
self.write_file_all(file_all_datas)
def find_str_coordinate(self,datas):
find_info = []
rest = []
data_cont = 1
with open( self.file_path, 'r', encoding='utf-8') as file:
for line in file:
if(datas in line):
find_info.append(data_cont)
rest.append(line)
data_cont+=1
if len(find_info) > 0:
dic_rest = dict(map(lambda x,y:[x,y],find_info,rest))
return dic_rest
else:
print("not find "+str(datas)+" from file.")
def get_file_attribute_list(self):
if self.examine_file() == True:
'''
st_mode: inode 保护模式
-File mode: file type and file mode bits (permissions).
st_ino: inode 节点号。
-Platform dependent, but if non-zero, uniquely identifies the file for a given value of st_dev.
——the inode number on Unix,
——the file index on Windows
st_dev: inode 驻留的设备。
-Identifier of the device on which this file resides.
st_nlink:inode 的链接数。
-Number of hard links.
st_uid: 所有者的用户ID。
-User identifier of the file owner.
st_gid: 所有者的组ID。
-Group identifier of the file owner.
st_size:普通文件以字节为单位的大小;包含等待某些特殊文件的数据。
-Size of the file in bytes, if it is a regular file or a symbolic link. The size of a symbolic link is the length of the pathname it contains, without a terminating null byte.
st_atime: 上次访问的时间。
-Time of most recent access expressed in seconds.
st_mtime: 最后一次修改的时间。
-Time of most recent content modification expressed in seconds.
st_ctime:由操作系统报告的"ctime"。在某些系统上(如Unix)是最新的元数据更改的时间,在其它系统上(如Windows)是创建时间(详细信息参见平台的文档)。
st_atime_ns
-Time of most recent access expressed in nanoseconds as an integer
st_mtime_ns
-Time of most recent content modification expressed in nanoseconds as an integer.
st_ctime_ns
-Platform dependent:
——the time of most recent metadata change on Unix,
——the time of creation on Windows, expressed in nanoseconds as an integer.
---------------------
'''
attribute_list = os.stat(self.file_path)
print(attribute_list)
file_modif_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(attribute_list.st_mtime))
print("文件的修改时间 : "+file_modif_time)
file_access_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(attribute_list.st_atime))
print("文件的上次访问时间 : "+file_access_time)
file_size = attribute_list.st_size/1024
print("文件大小 : "+str(file_size)+"KB")
file_attribute_rest = {"file_size":file_size,"file_modif_time":file_modif_time,"file_access_time":file_access_time}
return file_attribute_rest
def get_file_dir(self):
return os.path.dirname(os.path.abspath(self.file_path))
def copy_file(self, targetDir):
if self.examine_file() == True:
input_file = str(self.get_file_dir())
targetDir_list = targetDir.split("/")
if targetDir_list == input_file.split("\\"):
file_new_name = self.file_path.split(".")[0]+"_mancopy."+self.file_path.split(".")[1]
print(file_new_name)
shutil.copy(self.file_path, file_new_name)
else:
shutil.copy(self.file_path, targetDir)
def del_file(self):
if self.examine_file() == True:
os.remove(self.file_path)
def move_file(self,dstfile):
if self.examine_file() == True:
input_file = str(self.get_file_dir())
dstfile_list = dstfile.split("/")
if dstfile_list == input_file.split("\\"):
pass
else:
shutil.move(self.file_path,dstfile)
class Json_File_Man(Man_File_handle):
"""
Json 文件 增删改查
继承 Man_File_handle
"""
def __init__(self, file_path):
Man_File_handle.__init__(self, file_path)
def class_name(self):
print("Json_File_Man --> Man_File_handle.")
def add_json_data(self,datas):
if self.examine_file() == True:
with open( self.file_path, 'a+', encoding='utf-8') as file:
input_data = str(datas)
input_data = input_data.replace("\n","")
if input_data[0] != '{':
input_data = '{' + input_data
if input_data[-1] != '}':
input_data = input_data + '}'
input_data = input_data.replace("\'","\"")
file.write(input_data+"\n")
def del_json_data(self,datas):
print('del_json_data')
if self.examine_file() == True:
pass
def update_json_data(self,datas):
print('update_json_data')
if self.examine_file() == True:
pass
def select_json_data(self,datas):
print('select_json_data')
if self.examine_file() == True:
pass
class Ini_File_Man(Man_File_handle):
"""
ini 文件 增删改查
继承 Man_File_handle
"""
def __init__(self, file_path, cfg_debug=False ):
Man_File_handle.__init__(self, file_path)
self.config = configparser.ConfigParser()
self.cfg_debug = cfg_debug
def __read_ini_file(self):
if self.examine_file() == True:
try:
self.config.read(self.file_path)
except Exception as e:
if self.cfg_debug == True:
print(e)
else:
pass
def __submit_operation(self):
self.config.write(open(self.file_path, "w"))
def class_name(self):
print("Ini_File_Man --> Man_File_handle.")
def get_all_sections(self):
self.__read_ini_file()
lists_header = self.config.sections()
return lists_header
def get_default_data(self):
self.__read_ini_file()
return self.config.defaults()
def get_section_item_value(self, section, item):
self.__read_ini_file()
try:
value = self.config.get(section, item)
return value
except Exception as e:
print("repetition data")
def get_section_item(self, section):
self.__read_ini_file()
item_list = []
for item in self.config[section]:
item_list.append(item)
return item_list
def get_section_option(self, section):
self.__read_ini_file()
return self.config.options(section)
def get_section_all(self, section):
self.__read_ini_file()
return self.config.items(section)
def judge_section(self, section):
self.__read_ini_file()
return section in self.config
def judge_option(self, section, option):
self.__read_ini_file()
boolean = self.config.has_option(section, option)
return boolean
def add_section(self, section):
self.__read_ini_file()
self.config.add_section(section)
self.__submit_operation()
def add_a_data(self, section, option, datas):
self.__read_ini_file()
if self.judge_section(section) == True:
pass
elif self.judge_section(section) == False:
self.config.add_section(section)
if self.judge_option(section,option) == False:
self.config.set(section, option, datas)
self.__submit_operation()
elif self.judge_option(section,option) == True:
print("[Warning] : already exist!")
else:
print("[Warning] : unusual!")
def del_section(self, section):
self.__read_ini_file()
self.config.remove_section(section)
self.__submit_operation()
def del_option(self, section, option):
self.__read_ini_file()
self.config.remove_option(section,option)
self.__submit_operation()
def update_init_data(self, section, option, datas):
self.__read_ini_file()
if self.judge_section(section) == True:
if self.judge_option(section,option) == True:
self.config.set(section, option, datas)
self.__submit_operation()
elif self.judge_option(section,option) == False:
print("[Warning] : Not Find "+str(option))
else:
print("[Warning] : unusual!")
elif self.judge_section(section) == False:
print("[Warning] : Not Find "+str(section))
def select_init_data(self, datas):
print('select_init_data')
'''
# has_section(section) # 是否存在该节
boolean = config.has_section("mysql")
boolean = config.has_option("mysql", "ip") # 是否存在指定节的选项
configparser.MAX_INTERPOLATION_DEPTH # 使用默认插值时, 当raw=false,get()递归插值的最大深度
config.clear() # 所有节都包含'DEFAULT'值,对节的清空不会删除'DEFAULT'值
config.BOOLEAN_STATES.update({'enabled': True, 'disabled': False}) # 自定义boolean的判断
config.SECTCRE = re.compile(r"\[ *(?P[^]]+?) *\]") # 自定义节头的编译与解析的正则表达式(去除左右空格)
config.read_file(open('config.ini', encoding="utf-8-sig"))
# read_string(string, source='') # 从字符串解析配置数据
config.read_string(config_str)
# read_dict(dictionary, source='') # 读取字典
config.read_dict({'section1': {'key1': 'value1',
'key2': 'value2'},
'section2': {'key3': 'value3',
'key4': 'value4'}
})
'''
a_file_path = "D:/py_test/yibiao_Auto/unitys/test_json1.json"
b_test = "D:/py_test/yibiao_Auto/logs/test_logs_20190402101742.log"
c_test = 'D:/py_test/yibiao_Auto/unitys/test_json1_mancopy_mancopy.json'
ini_test = 'D:/py_test/yibiao_Auto/unitys/test.ini'
file = "D:/py_test/yibiao_Auto/unitys/test_json.json"
f = Man_File_handle(file)
json = Json_File_Man(a_file_path)
ini = Ini_File_Man(ini_test)
test_datas = """"你好": "2\n","1":'3'"""