def del_blank_line(filename): # 清除文件空白行 """ 清除文件空白行空白行 :param filename: 文件名称 :return: True 成功;False 失败 """ try: with open(filename, "r+", encoding="utf-8") as infp: lines = infp.readlines() # 把源文件内容读出来保存在lines中 with open(filename, "w+", encoding="utf-8") as outfp: for li in lines: if li.split(): # 判断是否为空白行 outfp.writelines(li) # 将操作后的源文件覆盖写回 except IOError: print("%s 文件不存在或无操作权限" % filename) return False else: return True
def get_ip_list(filename, repeat=False): """ 在文件中获取合法的IP地址 :param filename: 文件名称 :param repeat: 去除重复行,True去除,False不去除 :return: 返回ip地址序列 """ import re try: with open(filename, "r", encoding="utf-8") as file1: line = file1.read() pattern = re.compile( r"(?:\b(?:\d{1,2}|1\d{2}|2[0-4]\d|25[0-5])\b\.){3}(?:\d{1,2}|1\d{2}|2[0-4]\d|25[0-5])\b") list_ip = pattern.findall(line) if len(list_ip) == 0: return list_ip except IOError: print("%s 文件不存在或无操作权限" % filename) return False else: if repeat == True: return set(list_ip) elif repeat == False: return list_ip
def get_check_code(n = 6): """ 获取有大小写字母、数字组成的随机n位验证码 :param num: 验证码位数,默认为6 :return: 返回n位验证码 """ import random check_code = str() code = str() for i in range(n): ret = random.randint(0, 9) if ret == 0 or ret == 1 or ret == 4 or ret == 7: code = str(ret) elif ret == 2 or ret == 5 or ret == 8: code = chr(random.randint(65, 90)) elif ret == 3 or ret == 6 or ret == 9: code = chr(random.randint(97, 122)) check_code = check_code + code return check_code