题目一代码:

import os

统计文件夹中每种文件的个数

def count_files(path): file_dict = {} for root, dirs, files in os.walk(path): for file in files: # 获取文件后缀 suffix = file.split('.')[-1] if suffix in file_dict: file_dict[suffix] += 1 else: file_dict[suffix] = 1

# 打印结果
for suffix, count in file_dict.items():
    print(f'{suffix}:{count}个')

测试

count_files('文件夹路径')

输出结果:

txt:3个

doc:4个

jpg:6个

题目二代码:

使用字节输入流一次读取一个字节的方法将file01.txt的文件读取并打印

with open('D:/file01.txt', 'rb') as f: byte = f.read(1) while byte: print(byte.decode(), end='') byte = f.read(1) print()

使用字节输入流一次读取多个字节的方法将file01.txt的文件读取并打印

with open('D:/file01.txt', 'rb') as f: bytes = f.read(4) while bytes: print(bytes.decode(), end='') bytes = f.read(4) print()

题目三代码:

import shutil

在D盘中创建两个文件夹

os.mkdir('D:/img1') os.mkdir('D:/img2')

在img1中放置一个图片文件

with open('D:/img1/test.jpg', 'wb') as f: f.write(b'这里是图片的二进制数据')

将img1中的图片文件使用字节流复制到img2中

shutil.copyfile('D:/img1/test.jpg', 'D:/img2/test.jpg'

题目一统计一个文件夹中每种文件的个数并打印。打印格式如下:txt3个doc4个jpg6个…题目二在你计算机的一个盘比如D盘根目录下创建一个文件名字叫做file01txt。保存以下内容要求是单字节字符比如字母或者数字file01txt1 abcdef123456要求:1 使用字节输入流一次读取一个字节的方法将file01txt的文件读取并打印2 使用字节输入流一次读取多个字节的方法将file01tx

原文地址: https://www.cveoy.top/t/topic/frKv 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录