標籤:name ip地址 gif print utf-8 color 內容 nbsp 空白
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在檔案中擷取合法的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
擷取n位隨機驗證碼
Python 我的方法