鱼C论坛

 找回密码
 立即注册
查看: 1665|回复: 0

[技术交流] 《零基础入门学习Python》第30讲笔记:文件系统:介绍一个高大上的东西

[复制链接]
发表于 2017-7-30 10:43:34 | 显示全部楼层 |阅读模式

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

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

x
模块介绍
1.        OS:Operation System
Python是跨平台的语言,OS使我们无需担心平台

查询:扩展阅读
  1. >>> import os
  2. >>> os.getcwd()
  3. 'D:\\软件\\Python'
  4. >>> os. chdir('E:\\')
  5. >>> os.getcwd
  6. <built-in function getcwd>
  7. >>> os.getcwd()
  8. 'E:\\'
复制代码


‘.’指代当前目录,‘..’指代上一级目录(os.pardir)
  1. >>> os.curdir
  2. '.'
  3. >>> os.listdir(os.curdir)  # 列举当前目录文件名,也可以os.listdir(‘.’)
复制代码


os.path若干用法

相对路径 / 绝对路径

练习:
0.
  1. # 输入文件名/开始搜索的路径,搜索该文件名是否存在。
  2. # 若遇到文件夹,则进入文件夹继续搜索

  3. import os

  4. def search_file(start_dir, target):
  5.     os.chdir(start_dir)
  6.    
  7.     for each_file in os.listdir(os.curdir):
  8.         if each_file == target:  # 找到目标
  9.             print(os.getcwd() + os.sep + each_file)  # os.sep使程序更标准
  10.             # 当前目录 + 路径分隔符 + 文件名
  11.         if os.path.isdir(each_file):
  12.             search_file(each_file, target)  # 递归调用
  13.             os.chdir(os.pardir)             # 记得返回上一层目录!
  14.             
  15. start_dir = input('请输入待查找的初始目录:')
  16. target = input('请输入待查找的目标文件:')
  17. search_file(start_dir, target)
复制代码



1.
  1. # 输入开始搜索路径,查找该路径下所有的指定格式文件(mp4,avi,rmvb)
  2. # 并创建一个文件(VedioList.txt)存放找到的文件的路径

  3. import os

  4. def search_file(start_dir, target):
  5.     os.chdir(start_dir)
  6.    
  7.     for each_file in os.listdir(os.curdir):
  8.         ext = os.path.splitext(each_file)[1] # 获取后缀
  9.         if ext in target :
  10.             vedio_list.append(os.getcwd() + os.sep + each_file + os.linesep) # 使用os.sep让程序更标准
  11.         if os.path.isdir(each_file) :
  12.             search_file(each_file, target) # 递归调用
  13.             os.chdir(os.pardir) # 递归调用后切记返回上一层目录

  14. start_dir = input('请输入待查找的初始目录:')
  15. program_dir = os.getcwd()

  16. target = ['.mp4', '.avi', '.rmvb']
  17. vedio_list = []  # 存储对应格式文件路径

  18. search_file(start_dir, target)

  19. f = open(program_dir + os.sep + 'vedioList.txt', 'w')
  20. f.writelines(vedio_list)
  21. f.close()
复制代码


2.
  1. # 用户输入关键字,查找当前文件夹内(如果当前文件夹包含文件夹,则进入文件夹继续搜索)
  2. # 所有含有该关键字的文本文件(.txt后缀),要求显示该文件所在位置以及关键字在文件中的
  3. # 具体位置(第几行,第几个字符)

  4. import os

  5. def print_pos(key_dict):
  6.     keys = key_dict.keys()
  7.     keys = sorted(keys) # 由于字典是无序的,我们这里对行数进行排序
  8.     for each_key in keys:
  9.         print('关键字出现在第 %s 行,第 %s 个位置。' % (each_key, str(key_dict[each_key])))


  10. def pos_in_line(line, key):
  11.     pos = []
  12.     begin = line.find(key)
  13.     while begin != -1:
  14.         pos.append(begin + 1) # 用户的角度是从1开始数
  15.         begin = line.find(key, begin+1) # 从下一个位置继续查找

  16.     return pos


  17. def search_in_file(file_name, key):
  18.     f = open(file_name)
  19.     count = 0 # 记录行数
  20.     key_dict = dict() # 字典,用户存放key所在具体行数对应具体位置
  21.    
  22.     for each_line in f:
  23.         count += 1
  24.         if key in each_line:
  25.             pos = pos_in_line(each_line, key) # key在每行对应的位置
  26.             key_dict[count] = pos
  27.    
  28.     f.close()
  29.     return key_dict


  30. def search_files(key, detail):   
  31.     all_files = os.walk(os.getcwd())  # 遍历path,返回(path, [包含目录], [包含文件])
  32.     txt_files = []

  33.     for i in all_files:
  34.         for each_file in i[2]:
  35.             if os.path.splitext(each_file)[1] == '.txt': # 根据后缀判断是否文本文件
  36.                 each_file = os.path.join(i[0], each_file)
  37.                 txt_files.append(each_file)

  38.     for each_txt_file in txt_files:
  39.         key_dict = search_in_file(each_txt_file, key)
  40.         if key_dict:  # 字典内有内容
  41.             print('================================================================')
  42.             print('在文件【%s】中找到关键字【%s】' % (each_txt_file, key))
  43.             if detail in ['YES', 'Yes', 'yes']:
  44.                 print_pos(key_dict)


  45. key = input('请将该代码放于待查找的文件夹内,请输入关键字:')
  46. detail = input('请问是否需要打印关键字【%s】在文件中的具体位置(YES/NO):' % key)
  47. search_files(key, detail)
复制代码



3.
  1. # 编写一个程序,统计当前目录下每个文件类型的文件数
  2. import os


  3. all_files = os.listdir(os.curdir)  # 存储当前目录内的文件名
  4. type_dict = dict()  # 字典

  5. for each_file in all_files:
  6.     if os.path.isdir(each_file):  # 指定路径是否存在且是一个目录(即文件夹!)
  7.         type_dict.setdefault('文件夹', 0)  # 默认规则插入内容
  8.         type_dict['文件夹'] += 1
  9.     else:
  10.         ext = os.path.splitext(each_file)[1]  # 分离文件名、扩展名,只返回后者
  11.         type_dict.setdefault(ext, 0)
  12.         type_dict[ext] += 1

  13. for each_type in type_dict.keys():   # 遍历字典中的键
  14.     print('该文件夹下共有类型为【%s】的文件%d个' % \
  15.           (each_type, type_dict[each_type]))
复制代码



4.
  1. # 计算当前文件夹下所有文件的大小
  2. import os

  3. all_files = os.listdir(os.curdir)  # 存储当前目录内的文件名
  4. file_dict = dict()  # 字典

  5. for each_file in all_files:
  6.     if os.path.isfile(each_file):  
  7.         # 指定路径是否存在且是一个文件
  8.         file_size = os.path.getsize(each_file)  # 获取大小
  9.         file_dict[each_file] = file_size        # 存储

  10. for each in file_dict.items():
  11.     print('%s【%d Bytes】' % (each[0], each[1]))
复制代码














评分

参与人数 1鱼币 +3 收起 理由
小甲鱼 + 3

查看全部评分

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-4-28 07:02

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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