Python第三次作业【模块+IO】

Python第三次作业【模块+IO】 一、模块【题目】使用 os 和 os.path 以及函数的递归完成 给出一个路径遍历当前路径所有的文件及文件夹 打印输出所有的文件遇到文件输出路径遇到文件夹继续进文件夹【代码】import os from os import path def traverse_file(folder_path): name_list os.listdir(folder_path) for name in name_list: full_path path.join(folder_path, name) if path.isfile(full_path): print(full_path) elif path.isdir(full_path): traverse_file(full_path) if __name__ __main__: target_dir ./ traverse_file(target_dir)【截图】二、IO1、【题目】IO流‑文本编写程序读取article.txt统计文件中英文单词出现总数量只统计单词忽略数字、标点符号 并将统计结果写入result.txt。 要求使用with语法文件编码utf‑8。【代码】import string count 0 with open(article.txt, r, encodingutf-8) as f: content f.read() for c in content: if c in string.punctuation or c.isdigit(): content content.replace(c, ) words content.split() count len(words) with open(result.txt, w, encodingutf-8) as f: f.write(f英文单词总数{count})【截图】运行成功被读取文档 article.txt写入结果文档 result.txt2、【题目】IO流‑读写模式综合现有文件record.log编写代码1.如果文件不存在则创建2.在文件末尾追加一行2026‑07‑27 操作完成3.追加完成后读取文件全部内容打印到控制台。 提示注意光标位置选对打开模式。【代码】with open(record.log, a, encodingutf-8) as f: f.write(2026-07-27 操作完成\n) f.seek(0) all_text f.read() print(all_text)【截图】运行成功record.log文件3、【题目】模块‑自定义模块1.创建自定义模块math_tool.py内部实现两个函数 - calc_area(r)计算圆面积 - calc_circum(r)计算圆周长2.在另一个文件main.py用两种不同导入方式调用这两个函数 - 方式1import math_tool - 方式2from math_tool import calc_area, calc_circum 写出两个文件完整代码。【代码】math_tool.pyimport math def calc_area(r): return math.pi * r ** 2 def calc_circum(r): return 2 * math.pi * r print(calc_area(5)) print(calc_circum(5))math.py两个方法# 方式1 import math_tool print(math_tool.calc_area(2)) print(math_tool.calc_circum(2)) # 方式2 from math_tool import calc_area, calc_circum print(calc_area(3)) print(calc_circum(3))【截图】math_tool.pymath.py4、【题目】模块‑标准库os模块使用os标准库完成1.遍历当前文件夹打印所有后缀为.txt的文件名2.创建文件夹backup3.加判断条件如果backup文件夹已存在不要报错。【代码】import os for name in os.listdir(): if name.endswith(.txt): print(name) if not os.path.exists(backup): os.mkdir(backup)【截图】5、【题目】使用os和os.path以及函数的递归完成: 给出一个路径遍历当前路径所有的文件及文件夹 打印输出所有的文件遇到文件输出路径遇到文件夹继续进文件夹【代码】import os def find_all_file(path): for name in os.listdir(path): full_path os.path.join(path, name) if os.path.isfile(full_path): print(full_path) else: find_all_file(full_path) find_all_file(.)【截图】