马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
1. 调用os模块: import os, os模块中的函数使用方法:http://bbs.fishc.com/thread-45512-1-1.html
2. 030 动动手的程序实现:
import os
def seek_extension(path):
file_type = {}
file = os.listdir(path)
for each_file in file:
file_name_extension = os.path.splitext(each_file)
if file_name_extension[1] not in file_type:
file_type[file_name_extension[1]] = 1
else:
file_type[file_name_extension[1]] += 1
if '' in file_type:
file_type.setdefault('文件夹', file_type[''])
file_type.pop('')
for eachkey in file_type.keys():
print("该文件夹下共有类型为【%s】的文件 %d 个" % ( eachkey, file_type[eachkey] ) )
path = input("输入要查找的绝对路径: ")
seek_extension(path)
import os
def file_size_calc(path):
file = os.listdir(path)
file_size = {}
for each_file in file:
file_size[each_file] = os.path.getsize(path + '\\' + each_file) #os.path.getsize(path) 中 path为绝对路径
for each_key in file_size.keys():
print('%s 【%d bytes】' % ( each_key, file_size[each_key] ) )
path = input("请输入要查找位置的绝对路径: ")
file_size_calc(path)
import os
def find_file(path, file):
os.chdir(path)
for each_file in os.listdir( os.curdir ):
if os.path.isdir(each_file):
find_file(each_file, file)
os.chdir('..')
if each_file == file:
print(os.getcwd() + os.sep + each_file)
path = input("请输入待查找的初始目录: ")
file = input("请输入需要查找的目标文件: ")
find_file(path, file)
import os
file_format = ['.mp4', '.rmvb', '.avi']
save_filepath = list()
def search_file(path):
os.chdir(path)
for each_file in os.listdir(os.curdir):
if os.path.isdir(each_file):
search_file(each_file)
os.chdir(os.pardir)
if os.path.splitext(each_file)[1] in file_format:
save_filepath.append(os.getcwd() + os.sep + each_file)
f = open('D:\\python\\python_study\\vediolist.txt', 'w')
for each in save_filepath:
f.writelines(each + '\n')
f.close()
path = input("请输入带查找的初始目录: ")
search_file(path)
import os
def pos_in_line(line, key):
pos = []
begin = line.find(key)
while begin != -1:
pos.append(begin + 1)
begin = line.find(key, begin + 1)
return pos
def pos_in_file(file, key):
dict_key = dict()
count = 0
target_file = open(file)
for each_line in target_file:
count += 1
if key in each_line:
pos = pos_in_line(each_line, key)
dict_key[count] = pos
target_file.close()
return dict_key
def print_key(dict_key):
keys = dict_key.keys()
keys = sorted(keys)
for each_key in keys:
print("关键字出现在第 %s 行, 第 %s 个位置" % ( each_key, dict_key[each_key] ) )
def search_key(path, key):
os.chdir(path)
for each_file in os.listdir(os.curdir):
if os.path.isdir(each_file):
search_key(each_file, key)
os.chdir(os.pardir)
if os.path.isfile(each_file):
if os.path.splitext(each_file)[1] == '.txt':
dict_key = pos_in_file(each_file, key)
if dict_key != {}:
print('==================================================================================')
print("在文件【%s】中找到关键字【%s】" %( (os.getcwd() + os.sep + each_file), key ) )
print_key(dict_key)
path = input("请输入要查找的路径: ")
key = input("请输入要查找的关键字: ")
search_key(path, key)
|