1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
| import os FILE_DIR = os.path.dirname(os.path.abspath(__file__))
def get_filelist1(dir, postfix): ''' 按照后缀返回文件名列表 INPUT -> 目录地址, 文件后缀 OUTPUT -> 文件名列表 ''' return [os.path.join(dir, f) for f in os.listdir(dir) if f.endswith(postfix)]
def get_filelist2(dir, preffix): ''' 按照前缀返回文件名列表 INPUT -> 目录地址, 文件前缀 OUTPUT -> 文件名列表 ''' return [os.path.join(dir, f) for f in os.listdir(dir) if f.startswith(preffix)]
def get_file_postfix(filename): ''' 获取文件名后缀 INPUT -> 文件名 OUTPUT -> 文件后缀 ''' file = os.path.splitext(filename) preffix, postfix = file return postfix
def get_file_preffix(filename): ''' 获取文件名前缀 INPUT -> 文件名 OUTPUT -> 文件前缀 ''' file = os.path.splitext(filename) preffix, postfix = file return preffix
def file_chunkspilt(path, filename, chunksize): ''' 文件按照数据块大小分割为多个子文件 INPUT -> 文件目录, 文件名, 每个数据块大小 ''' if chunksize > 0: filepath = path+'/'+filename partnum = 0 inputfile = open(filepath, 'rb') while True: chunk = inputfile.read(chunksize) if not chunk: break partnum += 1 newfilename = os.path.join(path, (filename+'_%04d' % partnum)) sub_file = open(newfilename, 'wb') sub_file.write(chunk) sub_file.close() inputfile.close() else: print('chunksize must bigger than 0!')
def file_linespilt(path, filename, limit): ''' 文件按照行分割成多个子文件 INPUT -> 文件目录, 文件名, 行数 ''' if limit > 0: preffix = get_file_preffix(filename) postfix = get_file_postfix(filename) file_count = 0 l_list = [] with open(path+'/'+filename, 'rb') as f: for line in f: l_list.append(line) if len(l_list) < limit: continue subfile = preffix+"_"+str(file_count)+"."+postfix with open(FILE_DIR+'/'+subfile, 'wb') as file: for l in l_list[:-1]: file.write(l) file.write(l_list[-1].strip()) l_list=[] file_count += 1 else: print('limit must bigger than 0!')
def file_combine(path, filename): ''' 子文件合并 INPUT -> 文件目录, 文件名 ''' filepath = path+'/'+filename partnum = 0 outputfile = open(filepath, 'wb') subfile_list = get_filelist2(FILE_DIR, filename+'_') for subfile in subfile_list: temp = open(subfile, 'rb') outputfile.write(temp.read()) temp.close() outputfile.close()
|