|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 qq33zz 于 2018-6-29 18:31 编辑
动动手0
- import os
- all_files = os.listdir(os.curdir)
- type_dict = {}
- for each_file in all_files:
- if os.path.isdir(each_file):
- type_dict.setdefault('文件夹', 0)
- type_dict['文件夹'] += 1
- else:
- ext = os.path.splitext(each_file)[1]
- type_dict.setdefault(ext, 0)
- type_dict[ext] += 1
- for each_type in type_dict.keys():
- print('该文件夹下共有类型为【%s】的文件 %d 个' % (each_type, type_dict[each_type]))
复制代码
动动手1
- import os #计算文件大小
- all_files = os.listdir(os.curdir)
- for each_file in all_files:
- if os.path.isfile(each_file):
- print('%s[%d]'%(each_file,os.path.getsize(each_file)))
- elif os.path.isdir(each_file):
- print('文件夹名:%s'%each_file)
- import os
- def defind(star_path,file_input):
- os.chdir(star_path)
- for each_file in os.listdir(os.curdir):
- if each_file == file_input:
- print(os.getcwd()+os.sep+each_file)
- if os.path.isdir(each_file):
- defind(each_file,file_input)
- os.chdir(os.pardir)
- star_path = input('请输入需要搜索的路径:')
- file_input = input('请输入需要查找的文件名:' )
- defind(star_path,file_input)
复制代码
动动手2
- import os #查找路径下指定后缀名
- def defind(star_path,suffix):
- os.chdir(star_path)
- for each_file in os.listdir(os.curdir):
- if os.path.splitext(each_file)[1] in suffix:
- file.write(os.getcwd()+os.sep+each_file+'\n')
- if os.path.isdir(each_file):
- defind(each_file,suffix)
- os.chdir(os.pardir)
- file = open('list.txt', 'a')
- suffix = ['.txt','.py']
- star_path = input('请输入需要查询的路径:')
- defind(star_path,suffix)
复制代码
动动手3
- import os
- def scan_file(key,user_input): #查找文件
- txt_file=[]
- all_file = os.walk(os.getcwd())
- for i in all_file:
- for each_file in i[2]:
- if os.path.splitext(each_file)[1] == '.txt':
- each_file=os.path.join(i[0],each_file)
- txt_file.append(each_file)
- for file in txt_file:
- str_position = scan_line(file, key)
- if str_position:
- print('=================================================================')
- print('在【%s】文件中发现【%s】关键词' % (file, key))
- for k in str_position.keys():
- if user_input in ['Y','y']:
- print('关键字被发现在第【%s】行第【%s】个字符'%(k,str_position[k]))
- return txt_file
- def scan_line(file1,key): #查找行
- line_result = {}
- count_line = 0
- b = open(file1)
- for each_line in b.readlines():
- count_line += 1
- if key in each_line:
- line_result[count_line] = scan_str(each_line,key)
- b.close()
- return line_result
- def scan_str(line,key): #查找字符
- str_result = []
- while line.find(key) != -1:
- str_result.append(line.find(key))
- break
- return str_result
- key = 'MJ'
- user_input = 'Y'
- scan_file(key,user_input)
复制代码
知识点:
1、python 把 0、空字符串、和none看成False。
2、return可以返回多个值。
3、os.walk()查找路径下所有文件包括子文件夹,返回一个三元组(dirpath目录路径,dirname目录下所有文件夹名,filename目录下所有文件名)。
4、os.curdir当前目录(没有参数)、¥os.chdir()路径跳转、os.pardir上级路径、¥os.getcwd()获取当前路径名、os.sep输入\、¥os.listdir()获取路径下所有文件
5、os.find()用于查找字符串在文件中的位置。差找不到返回-1 |
|