一、linux,基于文件大小,创建时间,修改时间,文件内容,文件名称等进行查找汇总和输出

2019-01-04

只操作文本文件

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*
  3. # Created by YangYongming at 2018/12/10 17:16
  4. # FileName: main.py
  5.  
  6. import os
  7. import time
  8. import zipfile
  9.  
  10. fileslist = [] # 文件列表
  11. if not os.path.exists("temporary"):
  12. os.popen("mkdir temporary &> /dev/null")
  13.  
  14. def zip_dir(dirname, zipfilename):
  15. filelist = []
  16. if os.path.isfile(dirname):
  17. filelist.append(dirname)
  18. else:
  19. for root, dirs, files in os.walk(dirname):
  20. for name in files:
  21. filelist.append(os.path.join(root, name))
  22.  
  23. zf = zipfile.ZipFile(zipfilename, "w", zipfile.zlib.DEFLATED)
  24. for tar in filelist:
  25. arcname = tar[len(dirname):]
  26. zf.write(tar, arcname)
  27. zf.close()
  28.  
  29. def Get_Cur_time():
  30. """
  31. # 获取当前日期和时间
  32. :return:
  33. """
  34. return time.strftime("%Y-%m-%d-%H-%M-%S")
  35.  
  36. def Judge_filetype(filename):
  37. """
  38. # 判断一个文件是都是文本文件
  39. :param filename: 文件名称
  40. :return:
  41. """
  42. res = os.popen("file %s" % filename)
  43. if "text" in res.read():
  44. return True
  45. else:
  46. return False
  47.  
  48. def Get_FilesList(path):
  49. """
  50. # 获取所有文件列表
  51. :param path: 文件夹目录
  52. :return: 所有文件绝对路径组成的列表
  53. """
  54. global fileslist
  55. for root, dir, files in os.walk(path):
  56. for i in files:
  57. file = os.path.join(root,i) # 拿到每个文件的绝对路径
  58. if os.path.isfile(file): # 判断一下是否是文件
  59. if Judge_filetype(file): # 判断是否是文本文件
  60. if os.access(file, os.R_OK): # 判断文件是都可读
  61. fileslist.append(file) # 添加到文件列表中
  62. return fileslist
  63.  
  64. def Content_Keyword(keyword):
  65. """
  66. # 基于文件内容关键字查询
  67. :param keyword: 关键字
  68. :return:
  69. """
  70. # 创建存储目录
  71. global number
  72. dir = "%s[Content:%s]" % (curtime, keyword)
  73. os.popen("cd temporary && mkdir %s" % dir)
  74. for i in fileslist:
  75. # 基于linux命令拿到匹配到文本的行号
  76. result_obj_line = os.popen("grep -n %s %s | cut -d: -f1" % (keyword, i))
  77. # 读取行号字符串
  78. result_line_seq = result_obj_line.read()
  79. # 把行号转换成序列,并且将序列内容连接到一起
  80. result_line = ''.join(result_line_seq.split())
  81. # 判断是否都为数字,如果不是全数字,说明匹配到的文本可能是二进制文件或者其他格式文件
  82. if result_line.isdigit():
  83. # 输出文件名称和具体的行号,使用split()把一个文件中匹配到的所有行放在一个数组中,防止字符串错乱显示
  84. print("\033[0;32;40m%s Line:%s\033[0m" % (i, result_line_seq.split()))
  85. number += 1
  86. # 匹配到的文件-p拷贝到指定文件夹
  87. os.popen("cd temporary && cp -p %s %s" % (i, dir))
  88. time.sleep(0.03)
  89.  
  90. return dir, number
  91.  
  92. def Name_Type_Keyword(keyword):
  93. """
  94. # 基于文件名称查找
  95. :param keyword: 关键字
  96. :return:
  97. """
  98. # 创建存储目录
  99. global number
  100. dir = "%s[NameType:%s]" % (curtime, keyword)
  101. os.popen("cd temporary && mkdir %s" % dir)
  102. for i in fileslist:
  103. # 拿到文件的基名
  104. basename = os.path.basename(i)
  105. # 在基名中查找keyword
  106. result_basename_obj = os.popen("echo %s | grep %s" % (basename, keyword))
  107. # 读取查找返回值
  108. result_basename = result_basename_obj.read()
  109. # 判断是否有匹配到的内容
  110. if result_basename.strip():
  111. # 输出文件名
  112. print("\033[0;32;40m%s\033[0m" % i)
  113. # copy到指定的目录
  114. os.popen("cd temporary && cp -p %s %s" % (i, dir))
  115. number += 1
  116. time.sleep(0.03)
  117. return dir, number
  118.  
  119. def Time_Keyword(start_time, end_time, timetype):
  120. """
  121. # 按照文件创建时间查询
  122. :param start_time: 起始时间:20181230103050
  123. :param end_time: 截止时间
  124. :timetype: ctime文件创建时间,mtime:文件修改时间
  125. :return:
  126. """
  127. global number
  128. # 创建存储目录
  129. dir = "%s[%s:%s-%s]" % (curtime, timetype, start_time.strip(), end_time.strip())
  130. os.popen("cd temporary && mkdir %s" % dir)
  131. # 拿到起始时间的时间数组
  132. start_timeArray = time.strptime(start_time, "%Y%m%d%H%M%S")
  133. end_timeArray = time.strptime(end_time, "%Y%m%d%H%M%S")
  134. # 拿到截止时间的时间戳
  135. strt_timeStamp = int(time.mktime(start_timeArray))
  136. end_timeStamp = int(time.mktime(end_timeArray))
  137. for i in fileslist:
  138. # 拿到文件时间戳
  139. if timetype == "ctime":
  140. time_Stamp = os.path.getctime(i)
  141. elif timetype == "mtime":
  142. time_Stamp = os.path.getmtime(i)
  143. # 文件创建时间的时间戳在起止时间的时间戳内则匹配
  144. if strt_timeStamp <= int(time_Stamp) <= end_timeStamp:
  145. # 拿到文件创建时间数组
  146. ctimeArray = time.localtime(time_Stamp)
  147. # 按照指定的时间格式 拿到文件创建时间
  148. otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", ctimeArray)
  149. # 输出匹配的文件名和创建时间
  150. print("\033[0;32;40m%s Time:%s\033[0m" % (i, otherStyleTime))
  151. # copy到指定的目录
  152. os.popen("cd temporary && cp -p %s %s" % (i, dir))
  153. number += 1
  154. time.sleep(0.03)
  155. return dir, number
  156.  
  157. def Size_Keyword(ge_size, le_size):
  158. """
  159. # 按照文件大小查找
  160. :param ge_size: 文件大小范围最小值[KB]
  161. :param le_size: 文件大小范围最大值[KB]
  162. :return:
  163. """
  164. # 创建存储目录
  165. global number
  166. dir = "%s[Size:%sKB-%sKB]" % (curtime, ge_size, le_size)
  167. os.popen("cd temporary && mkdir %s" % dir)
  168. for i in fileslist:
  169. size_B = os.path.getsize(i)
  170. size_KB = size_B / float(1024)
  171. if float(ge_size) <= size_KB <= float(le_size):
  172. # 输出文件名和文件大小
  173. print("\033[0;32;40m%s Size:%.2f KB\033[0m" % (i, size_KB))
  174. # copy到指定目录
  175. os.popen("cd temporary && cp -p %s %s" % (i, dir))
  176. number += 1
  177. time.sleep(0.03)
  178. return dir, number
  179.  
  180. if __name__ == '__main__':
  181. number = 0
  182. curtime = Get_Cur_time()
  183. os.popen("clear")
  184. print("\033[1;31;40m\nNote: Only text files can be manipulated\n\033[0m")
  185. path = input("\033[0;36;40mplease input absolute path:\033[0m")
  186. if not os.path.exists(path):
  187. print("\033[0;36;40m%s:Path does not exist!\033[0m" % path)
  188. exit(10)
  189. res_fileslist = Get_FilesList(os.path.abspath(path))
  190. print("\033[0;36;40mNumber of documents found: %s" % len(fileslist))
  191. msg = "1.Search based on file content\n" \
  192. "2.Search based on file name or type\n" \
  193. "3.Search based on file creation time\n" \
  194. "4.Search based on file modification time\n" \
  195. "5.Search based on file size\n"
  196. num = input("\033[0;36;40m%splease choose:\033[0m" % msg)
  197. if num == "":
  198. keyword = input("\033[0;36;40mPlease enter keyword:\033[0m")
  199. back = Content_Keyword(keyword.strip())
  200. zip_dir("temporary/%s" % back[0], "temporary/%s.zip" % back[0])
  201.  
  202. elif num == "":
  203. keyword = input("\033[0;36;40mPlease enter name keyword or type:\033[0m")
  204. back = Name_Type_Keyword(keyword.strip())
  205. zip_dir("temporary/%s" % back[0], "temporary/%s.zip" % back[0])
  206.  
  207. elif num == "":
  208. start_time = input("\033[0;36;40mPlease enter a start time:\033[0m")
  209. end_time = input("\033[0;36;40mPlease enter a end time:\033[0m")
  210. if bool(end_time) == False:
  211. end_time = time.strftime("%Y%m%d%H%M%S", time.localtime())
  212. if start_time.isdigit() and end_time.isdigit() and len(start_time) == 14 and len(end_time) == 14:
  213. back = Time_Keyword(start_time, end_time, timetype="ctime")
  214. zip_dir("temporary/%s" % back[0], "temporary/%s.zip" % back[0])
  215. else:
  216. print("\033[0;31;40mInput error!\033[0m")
  217. exit(3)
  218.  
  219. elif num == "":
  220. start_time = input("\033[0;36;40mPlease enter a start time:\033[0m")
  221. end_time = input("\033[0;36;40mPlease enter a end time:\033[0m")
  222. if bool(end_time) == False:
  223. end_time = time.strftime("%Y%m%d%H%M%S", time.localtime())
  224. if start_time.isdigit() and end_time.isdigit() and len(start_time) == 14 and len(end_time) == 14:
  225. back = Time_Keyword(start_time, end_time, timetype="mtime")
  226. zip_dir("temporary/%s" % back[0], "temporary/%s.zip" % back[0])
  227. else:
  228. print("\033[0;31;40mInput error!\033[0m")
  229. exit(4)
  230.  
  231. elif num == "":
  232. ge_size = input("\033[0;36;40mPlease enter a minimum file size[KB]:\033[0m")
  233. le_size = input("\033[0;36;40mPlease enter a maximum file size[KB]:\033[0m")
  234. if ge_size.isdigit() and le_size.isdigit():
  235. back = Size_Keyword(ge_size, le_size)
  236. zip_dir("temporary/%s" % back[0], "temporary/%s.zip" % back[0])
  237. else:
  238. print("\033[0;31;40mInput error!\033[0m")
  239. exit(5)
  240.  
  241. else:
  242. print("\033[0;31;40mInput error!\033[0m")
  243. exit(1)
  244.  
  245. try:
  246. print("\033[0;36;40mTotal number of documents: %s\033[0m" % back[1])
  247. except:
  248. pass

运行截图:

二、windows批量pingIP地址/地址段,

sfle:每行一个IP或者网段

upip:存放up的ip

downip: 存放down的ip

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*
  3. # Created by YangYongming at 2018/11/25 12:26
  4. # FileName: ping.py
  5.  
  6. import os
  7. import IPy
  8. import queue
  9. import threading
  10. import time
  11.  
  12. class MyThread(threading.Thread):
  13. def __init__(self, queue):
  14. threading.Thread.__init__(self)
  15. self.queue = queue
  16.  
  17. def run(self): # 定义每个线程要运行的函数
  18. global aliveip
  19. global downip
  20. while True:
  21. host = self.queue.get(timeout=2) # 从队列中取Ip
  22. host = str(host)
  23. res = os.popen("ping -n 3 %s" % host)
  24. os.popen("exit\n")
  25. if "ms" not in res.read():
  26. print(">>> %s is Down" % host)
  27. downip.append(host)
  28. else:
  29. print(">>> %s is UP" % host)
  30. aliveip.append(host)
  31. self.queue.task_done()
  32. if self.queue.empty(): # 当队列为空时,终止该线程
  33. break
  34.  
  35. if __name__ == '__main__':
  36. start = time.time() # 程序开始时间
  37. print("\n Yongming working for you......\n")
  38. print("\n start......\n")
  39. with open("upip", "w", encoding="utf-8") as tmp1, open("downip", "w", encoding="utf-8") as tmp2:
  40. pass # 清空文件
  41. threadlist = [] # 线程列表
  42. queue = queue.Queue() # 队列
  43. aliveip = [] # UP IP列表
  44. downip = [] # DOWN IP列表
  45. num = 0 # 线程数量
  46. with open("sfile", "r", encoding="utf-8") as f1:
  47. for line in f1.readlines(): # 读取IP文件
  48. ip = IPy.IP(line) # 获取每个网段的IP地址列表
  49. for x in ip:
  50. num += 1 # 计算有多少个IP地址,决定开多少线程
  51. queue.put(x) # 向队列里面放IP
  52. if num >= 100:
  53. num = 100 # 设置线程数量不超过100
  54. for i in range(num):
  55. t = MyThread(queue) # 建立线程,传入队列
  56. t.setDaemon(False) # 主线程执行完成,等待所有的前台线程执行完毕,默认[等待]False
  57. t.start() # 线程准备就绪,等待CPU调度
  58.  
  59. queue.join() # 队列为空在进行以下操作
  60.  
  61. with open("downip", "a", encoding="utf-8") as f1:
  62. for i in downip:
  63. f1.write(i + '\n') # DOWN的IP写入文件
  64. with open("upip", "a", encoding="utf-8") as f2:
  65. for i in aliveip:
  66. f2.write(i + '\n') # UP的IP写入文件
  67.  
  68. end = time.time() # 结束时间
  69. elapsed = end - start # 计算总耗时
  70. print("\nUP:%s" % len(aliveip)) # 输出UP的IP数量
  71. print("DOWN:%s" % len(downip)) # 输出DOWN的IP数量
  72. print("\nTime taken: %d seconds\n" % elapsed) # 输出总耗时
  73. input("\nEnter to Quit:")
  74. time.sleep(30) # 等待10s退出

运行截图:

三,比较AB两个IP列表的不同

Afile:存储AIP列表

Bfile:存储BIP列表

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*
  3. # Created by YangYongming at 2018/12/04 14:53
  4. # FileName: ipCompar.py
  5.  
  6. def Check_Ip(filename):
  7. with open(filename, "r", encoding="utf-8") as file1:
  8. for i in file1.readlines():
  9. try:
  10. IP(i.strip())
  11. except Exception:
  12. if i.strip():
  13. print("[Err]IP address format: %s in %s" % (i.strip(), filename))
  14. else:
  15. print("[Err]There are blank lines: in %s" % filename)
  16. exit(100)
  17.  
  18. def Contrast_Ip(Afile, Bfile):
  19. excle = xlwt.Workbook(encoding="utf-8")
  20. sheet = excle.add_sheet('sheet 1')
  21.  
  22. style0 = xlwt.XFStyle()
  23. al = xlwt.Alignment()
  24. al.horz = 0x02
  25. al.vert = 0x01
  26. style0.alignment = al
  27. pattern = xlwt.Pattern()
  28. pattern.pattern = xlwt.Pattern.SOLID_PATTERN
  29. pattern.pattern_fore_colour = xlwt.Style.colour_map['gray40']
  30. style0.pattern = pattern
  31.  
  32. style1 = xlwt.XFStyle()
  33. al = xlwt.Alignment()
  34. al.horz = 0x02
  35. al.vert = 0x01
  36. style1.alignment = al
  37.  
  38. for i in range(0, 3):
  39. col = sheet.col(i)
  40. col.width = 256 * 20
  41.  
  42. sheet.write(0, 0, 'Only_IN_%s' % Afile, style0)
  43. sheet.write(0, 1, 'Only_IN_%s' % Bfile, style0)
  44. sheet.write(0, 2, 'Both', style0)
  45.  
  46. with open(Afile, "r+") as file1:
  47. A_ip = file1.readlines()
  48. for i in range(0, len(A_ip)):
  49. A_ip[i] = A_ip[i].strip()
  50. A_IPSET = set(A_ip)
  51.  
  52. with open(Bfile, "r+") as file2:
  53. B_ip = file2.readlines()
  54. for i in range(0, len(B_ip)):
  55. B_ip[i] = B_ip[i].strip()
  56. B_IPSET = set(B_ip)
  57.  
  58. for i, k in enumerate(A_IPSET.difference(B_IPSET), 1):
  59. sheet.write(i, 0, str(k), style1)
  60.  
  61. for i, k in enumerate(B_IPSET.difference(A_IPSET), 1):
  62. sheet.write(i, 1, str(k), style1)
  63.  
  64. for i, k in enumerate(B_IPSET.intersection(A_IPSET), 1):
  65. sheet.write(i, 2, str(k), style1)
  66.  
  67. excle.save("Ming[%s].xls" % Time)
  68.  
  69. return True
  70.  
  71. if __name__ == '__main__':
  72. import xlwt
  73. import time
  74. from IPy import IP
  75.  
  76. Time = time.strftime("%H-%M-%S")
  77. print("\nYongming working for you......\n")
  78. time.sleep(3)
  79.  
  80. Check_Ip(filename="Afile")
  81. Check_Ip(filename="Bfile")
  82.  
  83. if Contrast_Ip("Afile", "Bfile"):
  84. print("Success, please check Ming[%s.xls]" % Time)
  85. time.sleep(0.5)
  86. else:
  87. print("[Err] in Contrast_Ip()")
  88.  
  89. input("\nEnter to Quit:")
  90.  
  91. print("Quit after 3 seconds......")
  92.  
  93. time.sleep(3)

运行结果:会在当前目录生成一个excle文件,如下:

四:我的方法

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*
  3. # Created by YangYongming at 2018/11/19 17:46
  4. # FileName: ming.py
  5. import os
  6. import sys
  7. import zipfile
  8. import threading
  9. import queue
  10. import IPy
  11.  
  12. def Function_Validation(origin_func):
  13. """
  14. 对类的方法进行验证
  15. :param origin_func:源函数名称
  16. :return:源函数的返回值
  17. """
  18.  
  19. def wrapper(self, *args, **kwargs):
  20. """
  21. :param self: 可以直接调用类中的字段和方法
  22. :param args: 参数
  23. :param kwargs: 参数
  24. :return:
  25. """
  26. import hashlib
  27. md5 = hashlib.md5()
  28. # 对类识别码取MD5加密数据
  29. md5.update(bytes(str(self.password), encoding="utf-8"))
  30. if md5.hexdigest() != yangym.PASS:
  31. print("Error yangym()类识别码错误")
  32. exit(100)
  33. try:
  34. # 执行源函数
  35. u = origin_func(self, *args, **kwargs)
  36. # 返回原函数的返回值给外层函数
  37. return u
  38. except Exception:
  39. # self.revive() #不用顾虑,直接调用原来的类的方法
  40. return 'origin_func an Exception raised.'
  41.  
  42. return wrapper
  43.  
  44. class yangym():
  45. # 类入口验证码,实例化yangym时,必须携带PASS[password]字段,只有匹配才能执行类中的方法
  46.  
  47. PASS = "05a7319bcb20e06fa52a3dc3685f5f84"
  48.  
  49. def __init__(self, password):
  50. # password 实例化类的验证码。
  51. self.password = password
  52.  
  53. @Function_Validation
  54. def Del_Blank_Line(self, filename):
  55.  
  56. """
  57. 清除文件空白行空白行
  58. :param filename: 文件名称
  59. :return: True 成功;False 失败
  60. """
  61. try:
  62. with open(filename, "r+", encoding="utf-8") as infp:
  63. lines = infp.readlines() # 把源文件内容读出来保存在lines中
  64. with open(filename, "w+", encoding="utf-8") as outfp:
  65. for li in lines:
  66. if li.split(): # 判断是否为空白行
  67. outfp.writelines(li) # 将操作后的源文件覆盖写回
  68. except FileNotFoundError as e:
  69. print("[Err] No such file or directory: %s " % filename)
  70. return False
  71. except IOError:
  72. print("[Err] Permission deny: %s" % filename)
  73. return False
  74. except Exception as e:
  75. print("[Err:Del_Blank_Line()] %s" % e)
  76. return False
  77. else:
  78. return True
  79.  
  80. @Function_Validation
  81. def Get_IpList(self, filename, repeat=False):
  82. """
  83. 在文件中获取合法的IP地址
  84. :param filename: 文件名称
  85. :param repeat: 去除重复行,True去除,False不去除
  86. :return: 返回ip地址序列
  87. """
  88. import re
  89. try:
  90. with open(filename, "r", encoding="utf-8") as file1:
  91. line = file1.read()
  92. line = re.sub(r"[!@#$%^&*-+_~?/|\\]", " ", line)
  93. pattern = re.compile(
  94. 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")
  95. list_ip = pattern.findall(line)
  96. if len(list_ip) == 0:
  97. return list_ip
  98. except FileNotFoundError:
  99. print("[Err] No such file or directory: %s " % filename)
  100. return False
  101. except IOError:
  102. print("[Err] Permission deny: %s" % filename)
  103. return False
  104. except Exception as e:
  105. print("[Err:Get_IpList()] %s" % e)
  106. return False
  107. else:
  108. if repeat == True:
  109. return set(list_ip)
  110. elif repeat == False:
  111. return list_ip
  112.  
  113. @Function_Validation
  114. def Get_CheckCode(self, n=6):
  115. """
  116. 获取有大小写字母、数字组成的随机n位验证码
  117. :param num: 验证码位数,默认为6
  118. :return: 返回n位验证码
  119. """
  120. import random
  121. check_code = str()
  122. code = str()
  123. for i in range(n):
  124. ret = random.randint(0, 9)
  125. if ret == 0 or ret == 1 or ret == 4 or ret == 7:
  126. code = str(ret)
  127. elif ret == 2 or ret == 5 or ret == 8:
  128. code = chr(random.randint(65, 90))
  129. elif ret == 3 or ret == 6 or ret == 9:
  130. code = chr(random.randint(97, 122))
  131. check_code = check_code + code
  132. return check_code
  133.  
  134. @Function_Validation
  135. def SendMail(self, SenderName, SenderMail, Password, ReceList, Theme, Text, CcList=[], Appendix=None, Port=25, ):
  136. """
  137. 发送邮件
  138. :param SenderName: 发送者昵称
  139. :param SenderMail: 发送者邮箱
  140. :param Password: 邮箱密码/授权吗
  141. :param ReceList: 收件人列表
  142. :param Theme: 邮件主题
  143. :param Text: 邮件正文
  144. :param CcList: 抄送人列表[可选参数]
  145. :param Appendix: 附件全路径,不可以使用中文[可选参数]
  146. :param Port: 端口,[可选参数],默认"25"
  147. :return True:发送成功,False:发送失败
  148. """
  149. ret = True
  150. try:
  151. import smtplib, os
  152. from email.mime.text import MIMEText
  153. from email.utils import formataddr
  154. from email.mime.multipart import MIMEMultipart
  155. from email.mime.application import MIMEApplication
  156.  
  157. msg = MIMEMultipart('alternative')
  158.  
  159. msgText = MIMEText(Text, "Plain", "utf-8")
  160.  
  161. msg["from"] = formataddr([SenderName, SenderMail])
  162. msg["To"] = ",".join(ReceList)
  163. msg["Cc"] = ",".join(CcList)
  164. msg["Subject"] = Theme
  165.  
  166. if Appendix != None:
  167. attachName = os.path.basename(Appendix)
  168. part = MIMEApplication(open(Appendix, 'rb').read())
  169. part.add_header('Content-Disposition', 'attachment', filename=attachName)
  170. msg.attach(part)
  171.  
  172. msg.attach(msgText)
  173.  
  174. if Port == 25:
  175. server = smtplib.SMTP("smtp.163.com", 25)
  176. elif Port == 465:
  177. server = smtplib.SMTP_SSL("smtp.163.com", 465)
  178.  
  179. server.login(SenderMail, Password)
  180. server.sendmail(SenderMail, ReceList, msg.as_string())
  181. server.quit()
  182. except ModuleNotFoundError as e1:
  183. print("[Err] %s" % e1)
  184. ret = False
  185. except Exception as e2:
  186. print("[Err:SendMail()] %s" % e2)
  187. return ret
  188.  
  189. @Function_Validation
  190. def Copy_AToB_File(self, fileA, fileB):
  191. """
  192. 把文件A的内容追加到文件B中
  193. :param fileA: 源文件
  194. :param fileB: 目标文件
  195. :return: 成功返回True, 失败返回False
  196. """
  197. try:
  198. with open(fileA, "r", encoding="utf-8") as A, open(fileB, "r+", encoding="utf-8") as B:
  199. Afile = A.readlines()
  200. B.seek(0, 2)
  201. for i in Afile:
  202. B.writelines(i.strip() + "\n")
  203. except FileNotFoundError as e:
  204. print("[Err] %s" % e)
  205. return False
  206. else:
  207. return True
  208.  
  209. @Function_Validation
  210. def IpCount(self, ipfile):
  211. """
  212. 统计每个IP地址出现的次数
  213. :param ipfile: 包含纯IP地址的文件,每行一个,不要出现空白行
  214. :return: 返回一个字典{IP地址:次数,}
  215. """
  216. sip = []
  217. dic = {}
  218. try:
  219. with open(ipfile, "r+", encoding="utf-8") as f1:
  220. for i in f1.readlines():
  221. sip.append(i.strip())
  222. except FileNotFoundError:
  223. print("[Err] No such file or directory: %s " % ipfile)
  224. return False
  225. else:
  226. setip = set(sip)
  227. for i in setip:
  228. num = sip.count(i)
  229. dic[i] = num
  230. return dic
  231.  
  232. @Function_Validation
  233. def IpQuery(self, ip):
  234. """
  235. :param ip: IP地址
  236. :return: 执行成功返回归属地址信息,执行失败返回"False"
  237. """
  238. import requests
  239. from bs4 import BeautifulSoup
  240. url = 'http://m.ip138.com/ip.asp?ip='
  241. kv = {'User-Agent': 'Mozilla/5.0'}
  242. link = url + str(ip)
  243. try:
  244. r = requests.get(link, headers=kv)
  245. r.raise_for_status()
  246. r.encoding = r.apparent_encoding
  247. soup = BeautifulSoup(r.text, 'lxml')
  248. result = soup.select('p[class="result"]')[0].string
  249. return result
  250. except requests.HTTPError:
  251. return False
  252.  
  253. @Function_Validation
  254. def Get_FilesList(self, dirpath):
  255. fileslist = list()
  256. for root, dir, files in os.walk(dirpath):
  257. for i in files:
  258. file = os.path.join(root, i) # 拿到每个文件的绝对路径
  259. if os.path.isfile(file): # 判断一下是否是文件
  260. fileslist.append(file) # 添加到文件列表中
  261. return fileslist
  262.  
  263. @Function_Validation
  264. def zip_dir(self, dirname, zipfilename):
  265. """
  266. :param dirname: 需要打包的文件或目录名称
  267. :param zipfilename: 目标文件名
  268. :return:
  269. """
  270. filelist = list()
  271. if os.path.isfile(dirname):
  272. filelist.append(dirname)
  273. else:
  274. for root, dirs, files in os.walk(dirname):
  275. for name in files:
  276. filelist.append(os.path.join(root, name))
  277.  
  278. zf = zipfile.ZipFile(zipfilename, "w", zipfile.zlib.DEFLATED)
  279. for tar in filelist:
  280. arcname = tar[len(dirname):]
  281. zf.write(tar, arcname)
  282. zf.close()

Python练习1的更多相关文章

  1. Python中的多进程与多线程(一)

    一.背景 最近在Azkaban的测试工作中,需要在测试环境下模拟线上的调度场景进行稳定性测试.故而重操python旧业,通过python编写脚本来构造类似线上的调度场景.在脚本编写过程中,碰到这样一个 ...

  2. Python高手之路【六】python基础之字符串格式化

    Python的字符串格式化有两种方式: 百分号方式.format方式 百分号的方式相对来说比较老,而format方式则是比较先进的方式,企图替换古老的方式,目前两者并存.[PEP-3101] This ...

  3. Python 小而美的函数

    python提供了一些有趣且实用的函数,如any all zip,这些函数能够大幅简化我们得代码,可以更优雅的处理可迭代的对象,同时使用的时候也得注意一些情况   any any(iterable) ...

  4. JavaScript之父Brendan Eich,Clojure 创建者Rich Hickey,Python创建者Van Rossum等编程大牛对程序员的职业建议

    软件开发是现时很火的职业.据美国劳动局发布的一项统计数据显示,从2014年至2024年,美国就业市场对开发人员的需求量将增长17%,而这个增长率比起所有职业的平均需求量高出了7%.很多人年轻人会选择编 ...

  5. 可爱的豆子——使用Beans思想让Python代码更易维护

    title: 可爱的豆子--使用Beans思想让Python代码更易维护 toc: false comments: true date: 2016-06-19 21:43:33 tags: [Pyth ...

  6. 使用Python保存屏幕截图(不使用PIL)

    起因 在极客学院讲授<使用Python编写远程控制程序>的课程中,涉及到查看被控制电脑屏幕截图的功能. 如果使用PIL,这个需求只需要三行代码: from PIL import Image ...

  7. Python编码记录

    字节流和字符串 当使用Python定义一个字符串时,实际会存储一个字节串: "abc"--[97][98][99] python2.x默认会把所有的字符串当做ASCII码来对待,但 ...

  8. Apache执行Python脚本

    由于经常需要到服务器上执行些命令,有些命令懒得敲,就准备写点脚本直接浏览器调用就好了,比如这样: 因为线上有现成的Apache,就直接放它里面了,当然访问安全要设置,我似乎别的随笔里写了安全问题,这里 ...

  9. python开发编译器

    引言 最近刚刚用python写完了一个解析protobuf文件的简单编译器,深感ply实现词法分析和语法分析的简洁方便.乘着余热未过,头脑清醒,记下一点总结和心得,方便各位pythoner参考使用. ...

  10. 关于解决python线上问题的几种有效技术

    工作后好久没上博客园了,虽然不是很忙,但也没学生时代闲了.今天上博客园,发现好多的文章都是年终总结,想想是不是自己也应该总结下,不过现在还没想好,等想好了再写吧.今天写写自己在工作后用到的技术干货,争 ...

随机推荐

  1. fft的实现

    private static Complex[] FFT1(Complex[] f) { int N=f.length; int power= (int) (Math.log10(N)/Math.lo ...

  2. linux及安全第三周总结——跟踪分析LINUX内核的启动过程

    linux内核目录结构 arch目录包括了所有和体系结构相关的核心代码.它下面的每一个子目录都代表一种Linux支持的体系结构,例如i386就是Intel CPU及与之相兼容体系结构的子目录.PC机一 ...

  3. pom.xml mevan 的 配置文件

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/20 ...

  4. HTML5 Base64_encoding_and_decoding

    https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding In JavaSc ...

  5. VirtualBox 导入虚拟机时的注意事项 VDI 与VMDK

    1. 建议不要勾选  as vdi   vmdk 最好不过了.. 长个经验教训 以后尽量不勾选 vmdk 有很多工具能进行转换 vdi的 要麻烦一些.

  6. 《ERP系统原理与实施》

    第一 采购 第二 生产(生产任务->生产准备->加工单->派工单->生产调度->生产监控->数据采集->统计分析) 第三 仓储 第四 质量 第五 财务 第六 ...

  7. jenkins--svn+Email自动触发3(jenkins全局设置)

    全局java配置: 全局sonar-scanner插件配置:

  8. BZOJ2819Nim——树链剖分+线段树+Nim游戏

    题目描述 著名游戏设计师vfleaking,最近迷上了Nim.普通的Nim游戏为:两个人进行游戏,N堆石子,每回合可以取其中某一堆的任意多个,可以取完,但不可以不取.谁不能取谁输.这个游戏是有必胜策略 ...

  9. hdu 3727 Jewel (可持久化线段树+bit)

    链接: http://acm.hdu.edu.cn/showproblem.php?pid=3727 题意: 对一段序列进行四种操作: Insert x :在序列尾部插入一个x: Query_1 s ...

  10. git push -f

    有的时候使用GIT工作时,会遇到一下这种问题, Pushing to git@github.com:519ebayproject/519ebayproject.git To git@github.co ...