当前位置:网站首页>第030讲:文件系统:介绍一个高大上的东西 | 课后测试题及答案
第030讲:文件系统:介绍一个高大上的东西 | 课后测试题及答案
2022-06-22 20:05:00 【ChaseTimLee】
动动手:
0. 编写一个程序,统计当前目录下每个文件类型的文件数,程序实现如图:

import os
all_files = os.listdir(os.curdir) # 使用os.curdir表示当前目录更标准
file_dict = dict()
for each_file in all_files:
if os.path.isfile(each_file):
file_size = os.path.getsize(each_file)
file_dict[each_file] = file_size
for each in file_dict.items():
print('%s【%dBytes】' % (each[0], each[1]))
1. 编写一个程序,计算当前文件夹下所有文件的大小,程序实现如图:

import os
def search_file(start_dir, target) :
os.chdir(start_dir)
for each_file in os.listdir(os.curdir) :
if each_file == target :
print(os.getcwd() + os.sep + each_file) # 使用os.sep是程序更标准
if os.path.isdir(each_file) :
search_file(each_file, target) # 递归调用
os.chdir(os.pardir) # 递归调用后切记返回上一层目录
start_dir = input('请输入待查找的初始目录:')
target = input('请输入需要查找的目标文件:')
search_file(start_dir, target)
2. 编写一个程序,用户输入文件名以及开始搜索的路径,搜索该文件是否存在。如遇到文件夹,则进入文件夹继续搜索,程序实现如图:

import os
def search_file(start_dir, target) :
os.chdir(start_dir)
for each_file in os.listdir(os.curdir) :
if each_file == target :
print(os.getcwd() + os.sep + each_file) # 使用os.sep是程序更标准
if os.path.isdir(each_file) :
search_file(each_file, target) # 递归调用
os.chdir(os.pardir) # 递归调用后切记返回上一层目录
start_dir = input('请输入待查找的初始目录:')
target = input('请输入需要查找的目标文件:')
search_file(start_dir, target)
3. 编写一个程序,用户输入开始搜索的路径,查找该路径下(包含子文件夹内)所有的视频格式文件(要求查找mp4 rmvb, avi的格式即可),并把创建一个文件(vedioList.txt)存放所有找到的文件的路径,程序实现如图:

import os
def search_file(start_dir, target) :
os.chdir(start_dir)
for each_file in os.listdir(os.curdir) :
ext = os.path.splitext(each_file)[1]
if ext in target :
vedio_list.append(os.getcwd() + os.sep + each_file + os.linesep) # 使用os.sep是程序更标准
if os.path.isdir(each_file) :
search_file(each_file, target) # 递归调用
os.chdir(os.pardir) # 递归调用后切记返回上一层目录
start_dir = input('请输入待查找的初始目录:')
program_dir = os.getcwd()
target = ['.mp4', '.avi', '.rmvb']
vedio_list = []
search_file(start_dir, target)
f = open(program_dir + os.sep + 'vedioList.txt', 'w')
f.writelines(vedio_list)
f.close()
4. 编写一个程序,用户输入关键字,查找当前文件夹内(如果当前文件夹内包含文件夹,则进入文件夹继续搜索)所有含有该关键字的文本文件(.txt后缀),要求显示该文件所在的位置以及关键字在文件中的具体位置(第几行第几个字符),程序实现如图:

import os
def print_pos(key_dict):
keys = key_dict.keys()
keys = sorted(keys) # 由于字典是无序的,我们这里对行数进行排序
for each_key in keys:
print('关键字出现在第 %s 行,第 %s 个位置。' % (each_key, str(key_dict[each_key])))
def pos_in_line(line, key):
pos = []
begin = line.find(key)
while begin != -1:
pos.append(begin + 1) # 用户的角度是从1开始数
begin = line.find(key, begin+1) # 从下一个位置继续查找
return pos
def search_in_file(file_name, key):
f = open(file_name)
count = 0 # 记录行数
key_dict = dict() # 字典,用户存放key所在具体行数对应具体位置
for each_line in f:
count += 1
if key in each_line:
pos = pos_in_line(each_line, key) # key在每行对应的位置
key_dict[count] = pos
f.close()
return key_dict
def search_files(key, detail):
all_files = os.walk(os.getcwd())
txt_files = []
for i in all_files:
for each_file in i[2]:
if os.path.splitext(each_file)[1] == '.txt': # 根据后缀判断是否文本文件
each_file = os.path.join(i[0], each_file)
txt_files.append(each_file)
for each_txt_file in txt_files:
key_dict = search_in_file(each_txt_file, key)
if key_dict:
print('================================================================')
print('在文件【%s】中找到关键字【%s】' % (each_txt_file, key))
if detail in ['YES', 'Yes', 'yes']:
print_pos(key_dict)
key = input('请将该脚本放于待查找的文件夹内,请输入关键字:')
detail = input('请问是否需要打印关键字【%s】在文件中的具体位置(YES/NO):' % key)
search_files(key, detail)
边栏推荐
- The access succeeds but an exception is thrown: could not find acceptable representation
- 80- paging query, not only writing
- [palindrome structure of or36 linked list]
- Cannot re-register id: PommeFFACompetition-v0问题解决
- 一行代码为特定状态绑定SwiftUI视图动画
- 超快变形金刚 | 用Res2Net思想和动态kernel-size再设计 ViT,超越MobileViT
- 查询es分页下标超过1万
- MySQL adds (appends) prefix and suffix to a column field
- 百家讲坛 大秦崛起(下部)
- 【142. 环形链表 II】
猜你喜欢
![[redis]Redis6的主从复制](/img/47/3be33a0d7435bd75cdd6e7b4ea51d4.png)
[redis]Redis6的主从复制

杰理之外挂 4M 的 flash 在 PC 上查看大小只有 1M 的处理方法【篇】

优化求解器 | Gurobi的MVar类:矩阵建模利器、求解对偶问题的备选方案 (附详细案例+代码)

2022 chemical automation control instrument examination exercises and online simulation examination

HarmonyOS应用开发培训第二次
![[redis] publish and subscribe](/img/50/0c2fbbb8f56fccdd3222b77efdd723.png)
[redis] publish and subscribe

杰理之开启四声道通话近端卡顿问题【篇】

Operation of simulation test platform for 2022 Shandong safety officer C certificate test

长安旗下阿维塔科技增资扩股落定:宁德时代将持股约24%!

【160. 相交链表】
随机推荐
杰理之开启四声道通话近端变调问题【篇】
Apple corefoundation source code
redis学习笔记
Numpy learning notes (6) -- sum() function
2022 question bank and simulated examination for work license of main principals of hazardous chemical business units
[records of different objects required by QIPA]
超快变形金刚 | 用Res2Net思想和动态kernel-size再设计 ViT,超越MobileViT
查看苹果产品保修状态
[redis]集群与常见错误
[redis]Redis6的主从复制
85- have you learned any of these SQL tuning tips?
php 镜像制作
Five uses of 87 with as
513. 找树左下角的值 / 剑指 Offer II 091. 粉刷房子
软考必备资料大放送,全科目软考资料都给你备好了!
5分钟快速上线Web应用和API(Vercel)
53页智慧校园智能化系统设计方案(附下载)
[138. copy linked list with random pointer]
牛客 52次月赛 B牛牛的身高 (思维题 模拟题)
百家讲坛 雍正十三年(下部)