鱼C论坛

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

[技术交流] 旧版第030讲课后作业展示

[复制链接]
发表于 2022-10-26 18:56:35 | 显示全部楼层 |阅读模式

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

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

x
原帖地址:https://fishc.com.cn/thread-45649-1-1.html
本讲有关文件系统的操作编程,动动手共5道题目,如下是题目简述与小古比鱼编写的程序,感觉比小甲鱼老师提供的参考答案更简洁、更优雅!望各位鱼友走过路过,留下宝贵意见,共同交流进步!
0. 文件类型统计(统计当前目录下每个文件类型的文件数)

                               
登录/注册后可看大图
import os
ext = [os.path.splitext(file)[1] for file in os.listdir()]    # 将当前目录下各文件的扩展名存入列表ext
files = set(ext)                                              # 将ext去重后转换为集合files(文件类型)
for type in files:
    print(f"该文件夹下共有类型为【{type if type else '文件夹'}】的文件",ext.count(type),'个')    # 使用f-字符串输出
1. 文件大小统计(统计当前文件夹下所有文件的大小)

                               
登录/注册后可看大图
import os
for file in os.listdir():
    print(file,f'【{os.path.getsize(file)}Bytes】')
2. 文件查找(用户输入文件名以及开始搜索的路径,搜索该文件是否存在)

                               
登录/注册后可看大图
import os
path = input('请输入待查找的初始目录:')
file = input('请输入需要查找的目标文件:')
found = False
for each in os.walk(path):
    if file in each[2]:
        print(os.path.join(each[0],file))
        found = True
if not found:
    print('未查找到相关文件!')
3. 视频查找(查找用户输入的路径下所有mp4、rmvb、avi格式的视频文件,将路径保存在文件“vedioList.txt”中)

                               
登录/注册后可看大图
import os
path = input('请输入待查找的初始目录:')
found = []
for each in os.walk(path):
    for file in each[2]:
        if file.endswith(('.mp4','.rmvb','.avi')):
            found.append(os.path.join(each[0],file))

if found:
    f = open('vedioList_Guppy.txt','w')
    f.writelines('\n'.join(found))
    f.close()
else:
    print('未查找到相关文件!')
4. 文本关键字查找(查找当前文件夹内所有含有用户输入的关键字的文本文件,附带显示关键字具体位置的功能)

                               
登录/注册后可看大图
import os
import chardet

def check_charset(file):            # 函数check_charset()用于检测文本文件file的编码方式并返回
    with open(file,'rb') as f:
        data = f.read(4)
        charset = chardet.detect(data)['encoding']
    return 'gbk' if charset == 'ISO-8859-1' else 'utf-8'

key = input('请将该脚本放于待查找的文件夹内,请输入关键字:')
loc = input(f'请问是否需要打印关键字【{key}】在文件中的具体位置(YES/NO):') in ('YES','Yes','yes')
found = False
for each in os.walk('.'):
    for file in each[2]:
        if file.endswith('.txt'):
            path = os.path.join(each[0],file)
            f = open(path,encoding=check_charset(path))
            str = f.read()
            f.close()
            if key in str:
                print('==================================================================')
                print(f'在文件【{path}】中找到关键字【{key}】')
                found = True
                if loc:
                    list = str.split('\n')
                    for line in range(len(list)):
                        index = []
                        start = 0
                        while list[line].find(key,start) >= 0:
                            index.append(list[line].find(key,start)+1)
                            start = index[-1]
                        if index:
                            print(f'关键字出现在第 {line+1} 行,第 {index} 个位置。')
if not found:
    print(f'未找到含关键字【{key}】的文件!')
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-9-25 23:20

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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