鱼C论坛

 找回密码
 立即注册
查看: 3721|回复: 1

[学习笔记] A-14-OS模块练习

[复制链接]
发表于 2018-7-16 15:15:36 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. #coding: UTF-8

  2. #知识点总结
  3. #1.os模块即操作系统模块,详细文档http://bbs.fishc.org/thread-45512-1-1.html
  4. #2.


  5. #实操练习
  6. #1.查询文件夹下各种文件类型的个数
  7. #思路-利用os.listdir得到指定文件夹下各文件的名称,
  8. #之后通过循环,查找特定文件扩展名是否在已得到的文件名中,有则加一。最后输出即可。
  9. #优点:代码简单,思路清晰;缺点:需提前指定文件扩展名,未指定的无法监测其个数
  10. import os

  11. file_name = os.listdir('E:\\test')
  12. print(file_name)

  13. txt = 0
  14. png = 0
  15. py = 0
  16. docx = 0
  17. doc = 0

  18. for each_file in file_name:
  19.     if '.txt' in each_file:
  20.         txt += 1
  21.     elif '.png' in each_file:
  22.         png += 1
  23.     elif '.py' in each_file:
  24.         py += 1
  25.     elif '.docx' in each_file:
  26.         docx += 1
  27.     elif '.' not in each_file:
  28.         doc += 1

  29. print('txt 是 %d, png 是 %d, py 是 %d, docx 是 %d, doc 是 %d' % (txt,png,py,docx,doc))


  30. #2.改进版-查询文件夹下各种文件类型的个数
  31. #思路-通过os.listdir得到文件名称,再对文件名称进行遍历,分离出名称和扩展名
  32. #若扩展名在file_type字典中,其value值赋1;否则原value+1;之后进行下一次循环直到遍历结束
  33. #最后根据键值即文件扩展扩展名,遍历字典file_type输出value即可
  34. import  os

  35. def  seek_extension(path):
  36.     file_type = {}         #建立空字典,有key和value两部分
  37.     file_names = os.listdir(path)            #列举指定目录中的文件名,如a.txt,b.py,c.txt
  38.     for  each_file in file_names:
  39.         file_name_extension = os.path.splitext(each_file)  #分离文件名与扩展名,返回(f_name, f_extension)元组
  40.         if  file_name_extension[1] not in file_type:     #file_name_extension[1]此处即f_extension。
  41.                                                          #file_name_extension非元组嵌套元组,每次都是(name,ext...)
  42.             file_type[file_name_extension[1]] = 1    #例如file_name_extension[1]为txt,字典通过键值key(可为字符串)来精确索引
  43.         else:
  44.             file_type[file_name_extension[1]] += 1

  45.     for eachkey in file_type.keys():
  46.         print("该文件夹下共有类型为【%s】的文件 %d 个" % ( eachkey, file_type[eachkey] ) )

  47. path = input("输入要查找的绝对路径: ")
  48. seek_extension(path)


  49. #3.查询指定文件夹下各文件的大小
  50. #思路-通过os.listdir获得指定目录下文件名,遍历文件,其中通过os.path.getsize即可获得文件大小。
  51. #通过字典来存储文件名和其占用内存大小,遍历输出即可
  52. import os

  53. def  file_size_calc(path):
  54.     file = os.listdir(path)     #得到文件名构成列表如['a.txt','b.py']
  55.     file_size = {}              #key为文件名,value为文件大小,如{'asd.txt':141,'b.py':409}
  56.     for  each_file in file:
  57.         file_size[each_file] = os.path.getsize(path + '\\' + each_file)     #其中path为绝对路径,返回文件大小,单位字节

  58.     for  each_key in file_size.keys():
  59.         print('%s 【%d bytes】' % ( each_key, file_size[each_key] ) )


  60. path = input("请输入要查找位置的绝对路径: ")
  61. while not isabs(path)
  62. {
  63.     path = input("请输入要查找位置的绝对路径: ")
  64. }
  65. file_size_calc(path)


  66. #4.将指定目录下指定格式的文件保存的文件中
  67. import os

  68. doc_path = input('请输入待查找的初始目录:')
  69. while not os.path.isdir(doc_path):              #判断指定路径是否存在且是一个目录
  70.     doc_path = input('输入错误,请重新输入待查找的初始目录:')

  71. save_path=input('请输入文件保存目录:')
  72. while not os.path.isdir(save_path):              #判断指定路径是否存在且是一个目录
  73.     save_path = input('输入错误,请重新输入文件保存目录:')

  74. doc_walk = os.walk(doc_path)   #遍历doc_path路径下所有的子目录,返回一个三元组:(路径, [包含目录], [包含文件])

  75. file_path = []   #建立列表,存储文件地址

  76. for each_part in doc_walk:
  77.     for each_file in each_part[2]:
  78.         if '.avi' or '.mp4' or '.rmvb' in each_file.lower():
  79.             file_path.append(os.path.join(each_part[0],each_file) + '\n' * 2)  #将each_part[0],each_file组合成一个路径名
  80.                                                                                #将路径添加到列在file_path中
  81. print(file_path)

  82. f = open(save_path+'\\content2.txt','w',encoding = 'GBK')
  83. f.writelines(file_path)
  84. f.close()


  85. #5.没看懂,以后再说

  86. import os

  87. def  pos_in_line(line, key):
  88.     pos = []
  89.     begin = line.find(key)

  90.     while  begin != -1:
  91.         pos.append(begin + 1)
  92.         begin = line.find(key, begin + 1)

  93.     return pos

  94. def  pos_in_file(file, key):
  95.     dict_key = dict()
  96.     count = 0
  97.     target_file = open(file)

  98.     for  each_line in target_file:
  99.         count += 1
  100.         if  key in each_line:
  101.             pos = pos_in_line(each_line, key)
  102.             dict_key[count] = pos

  103.     target_file.close()
  104.     return dict_key

  105. def  print_key(dict_key):
  106.     keys = dict_key.keys()
  107.     keys = sorted(keys)
  108.     for  each_key in keys:
  109.         print("关键字出现在第 %s 行, 第 %s 个位置" % ( each_key, dict_key[each_key] ) )


  110. def  search_key(path, key):
  111.     os.chdir(path)

  112.     for  each_file in os.listdir(os.curdir):
  113.         if  os.path.isdir(each_file):
  114.             search_key(each_file, key)
  115.             os.chdir(os.pardir)
  116.         if  os.path.isfile(each_file):
  117.             if  os.path.splitext(each_file)[1] == '.txt':
  118.                 dict_key = pos_in_file(each_file, key)
  119.                 if  dict_key != {}:
  120.                     print('==================================================================================')
  121.                     print("在文件【%s】中找到关键字【%s】" %( (os.getcwd() + os.sep + each_file), key ) )
  122.                     print_key(dict_key)


  123. path = input("请输入要查找的路径: ")
  124. key = input("请输入要查找的关键字: ")
  125. search_key(path, key)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2022-8-9 16:23:06 | 显示全部楼层
请教一下:

#2.改进版-查询文件夹下各种文件类型的个数

这个地方的path是统一的绝对路径吗?
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-24 01:19

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表