当前位置: 首页 > news >正文

python从入门到精通(二十五):文件操作和目录管理难度分级练习题

文件操作和目录管理

    • 文件操作
      • 基础难度
        • 1. 简单文件写入
        • 2. 简单文件读取
        • 3. 追加内容到文件
      • 中级难度
        • 4. 逐行读取文件并统计行数
        • 5. 读取文件并提取特定信息
        • 6. 复制文件内容到新文件
      • 高级难度
        • 7. 处理二进制文件
        • 8. 批量文件处理
        • 9. 日志文件分析
      • 参考答案示例
        • 1. 简单文件写入
        • 2. 简单文件读取
        • 3. 追加内容到文件
        • 4. 逐行读取文件并统计行数
        • 5. 读取文件并提取特定信息
        • 6. 复制文件内容到新文件
        • 7. 处理二进制文件
        • 8. 批量文件处理
        • 9. 日志文件分析
    • 目录管理
      • 基础难度
        • 1. 创建目录
        • 2. 删除空目录
        • 3. 检查目录是否存在
      • 中级难度
        • 4. 遍历目录并打印文件
        • 5. 复制目录结构
        • 6. 重命名目录
      • 高级难度
        • 7. 批量删除指定类型的文件
        • 8. 统计目录下文件数量和总大小
        • 9. 按日期分类移动文件
      • 练习题答案示例
        • 1. 创建目录
        • 2. 删除空目录
        • 3. 检查目录是否存在
        • 4. 遍历目录并打印文件
        • 5. 复制目录结构
        • 6. 重命名目录
        • 7. 批量删除指定类型的文件
        • 8. 统计目录下文件数量和总大小
        • 9. 按日期分类移动文件
    • 文件操作和目录同时练习
      • 初级难度
        • 1. 创建目录并写入文件
        • 2. 读取指定目录下文件内容
        • 3. 删除目录下指定文件
      • 中级难度
        • 4. 遍历目录并统计文件数量和大小
        • 5. 复制目录及其内容
        • 6. 按文件类型分类整理目录
      • 高级难度
        • 7. 备份指定目录并压缩
        • 8. 递归清理空目录
        • 9. 分析目录结构并生成报告
      • 参考答案示例
        • 1. 创建目录并写入文件
        • 2. 读取指定目录下文件内容
        • 3. 删除目录下指定文件
        • 4. 遍历目录并统计文件数量和大小
        • 5. 复制目录及其内容
        • 6. 按文件类型分类整理目录
        • 7. 备份指定目录并压缩
        • 8. 递归清理空目录
        • 9. 分析目录结构并生成报告

以下是一系列使用 Python open 函数进行文件读写操作的练习题,难度逐步递增。

文件操作

基础难度

1. 简单文件写入

编写一个 Python 程序,使用 open 函数创建一个名为 test.txt 的文件,并向其中写入字符串 “Hello, World!”。

# 在此处编写代码
2. 简单文件读取

编写一个程序,使用 open 函数打开之前创建的 test.txt 文件,并读取其内容,然后将内容打印出来。

# 在此处编写代码
3. 追加内容到文件

使用 open 函数打开 test.txt 文件,以追加模式向文件中添加新的一行 “This is an additional line.”。

# 在此处编写代码

中级难度

4. 逐行读取文件并统计行数

编写一个 Python 程序,使用 open 函数打开一个文本文件(假设文件名为 large_text.txt),逐行读取文件内容,并统计文件的总行数,最后将行数打印出来。

# 在此处编写代码
5. 读取文件并提取特定信息

假设有一个文本文件 data.txt,其中每行包含一个姓名和一个年龄,用逗号分隔(例如:“Alice,25”)。编写一个程序,使用 open 函数读取该文件,提取出所有年龄大于 30 岁的人的姓名,并将这些姓名打印出来。

# 在此处编写代码
6. 复制文件内容到新文件

编写一个程序,使用 open 函数打开一个源文件(假设为 source.txt),将其内容复制到一个新的文件(假设为 destination.txt)中。

# 在此处编写代码

高级难度

7. 处理二进制文件

编写一个 Python 程序,使用 open 函数以二进制模式打开一个图片文件(例如 image.jpg),读取其内容,然后将内容写入一个新的图片文件(例如 new_image.jpg),实现图片的复制。

# 在此处编写代码
8. 批量文件处理

假设有一个文件夹,其中包含多个文本文件(扩展名为 .txt)。编写一个程序,使用 open 函数遍历该文件夹中的所有文本文件,统计每个文件中的单词数量,并将文件名和对应的单词数量写入一个新的文件 word_count_summary.txt 中。

# 在此处编写代码
9. 日志文件分析

假设有一个日志文件 log.txt,每行记录了一个事件,格式为 [时间戳] 事件描述。编写一个 Python 程序,使用 open 函数读取该日志文件,统计每个小时内发生的事件数量,并将结果写入一个新的文件 hourly_event_count.txt 中。

# 在此处编写代码

参考答案示例

1. 简单文件写入
with open('test.txt', 'w') as file:
    file.write('Hello, World!')
2. 简单文件读取
with open('test.txt', 'r') as file:
    content = file.read()
    print(content)
3. 追加内容到文件
with open('test.txt', 'a') as file:
    file.write('\nThis is an additional line.')
4. 逐行读取文件并统计行数
line_count = 0
with open('large_text.txt', 'r') as file:
    for line in file:
        line_count += 1
print(f"文件的总行数为: {line_count}")
5. 读取文件并提取特定信息
names = []
with open('data.txt', 'r') as file:
    for line in file:
        name, age = line.strip().split(',')
        if int(age) > 30:
            names.append(name)
print("年龄大于 30 岁的人的姓名:")
for name in names:
    print(name)
6. 复制文件内容到新文件
with open('source.txt', 'r') as source_file:
    content = source_file.read()
    with open('destination.txt', 'w') as dest_file:
        dest_file.write(content)
7. 处理二进制文件
with open('image.jpg', 'rb') as source_file:
    binary_data = source_file.read()
    with open('new_image.jpg', 'wb') as dest_file:
        dest_file.write(binary_data)
8. 批量文件处理
import os

folder_path = '.'  # 当前文件夹
with open('word_count_summary.txt', 'w') as summary_file:
    for filename in os.listdir(folder_path):
        if filename.endswith('.txt'):
            word_count = 0
            with open(os.path.join(folder_path, filename), 'r') as file:
                for line in file:
                    words = line.split()
                    word_count += len(words)
            summary_file.write(f"{filename}: {word_count} 个单词\n")
9. 日志文件分析
hourly_count = {}
with open('log.txt', 'r') as file:
    for line in file:
        timestamp = line.split(']')[0][1:].split(':')[0]
        if timestamp in hourly_count:
            hourly_count[timestamp] += 1
        else:
            hourly_count[timestamp] = 1
with open('hourly_event_count.txt', 'w') as output_file:
    for hour, count in hourly_count.items():
        output_file.write(f"{hour}:00 - {hour}:59: {count} 个事件\n")

目录管理

以下是不同难度级别的 Python 目录操作练习题,涵盖了创建、删除、遍历、重命名等常见的目录操作。

基础难度

1. 创建目录

编写一个 Python 程序,使用 os 模块创建一个名为 new_directory 的新目录。如果该目录已经存在,则输出提示信息。

import os

# 请在此处编写代码
2. 删除空目录

编写一个程序,使用 os 模块删除名为 empty_directory 的空目录。如果目录不存在,则输出相应的错误信息。

import os

# 请在此处编写代码
3. 检查目录是否存在

编写一个 Python 程序,检查名为 existing_directory 的目录是否存在。如果存在,输出 目录存在;如果不存在,输出 目录不存在

import os

# 请在此处编写代码

中级难度

4. 遍历目录并打印文件

编写一个程序,使用 os 模块遍历指定目录(假设为当前目录 .)下的所有文件和子目录,并打印出所有文件的名称。

import os

# 请在此处编写代码
5. 复制目录结构

编写一个 Python 程序,将一个源目录(例如 source_dir)的目录结构复制到目标目录(例如 target_dir),但不复制文件内容,只复制目录结构。

import os

# 请在此处编写代码
6. 重命名目录

编写一个程序,使用 os 模块将名为 old_name 的目录重命名为 new_name。如果原目录不存在,输出相应的错误信息。

import os

# 请在此处编写代码

高级难度

7. 批量删除指定类型的文件

编写一个 Python 程序,遍历指定目录(例如 data_dir)及其子目录,删除所有扩展名为 .tmp 的临时文件。

import os

# 请在此处编写代码
8. 统计目录下文件数量和总大小

编写一个程序,统计指定目录(例如 stats_dir)下的文件数量和所有文件的总大小(以字节为单位),并输出统计结果。

import os

# 请在此处编写代码
9. 按日期分类移动文件

假设在一个目录(例如 unsorted_dir)中有很多文件,文件名包含日期信息(例如 2023-01-01_file.txt)。编写一个 Python 程序,根据文件名中的日期信息,将文件移动到以日期命名的子目录中(例如 2023-01-01 目录)。

import os
import shutil

# 请在此处编写代码

练习题答案示例

1. 创建目录
import os

directory = 'new_directory'
if not os.path.exists(directory):
    os.mkdir(directory)
    print(f'目录 {directory} 创建成功!')
else:
    print(f'目录 {directory} 已经存在!')
2. 删除空目录
import os

directory = 'empty_directory'
if os.path.exists(directory):
    if os.path.isdir(directory) and len(os.listdir(directory)) == 0:
        os.rmdir(directory)
        print(f'目录 {directory} 删除成功!')
    else:
        print(f'目录 {directory} 不是空目录,无法删除!')
else:
    print(f'目录 {directory} 不存在!')
3. 检查目录是否存在
import os

directory = 'existing_directory'
if os.path.exists(directory) and os.path.isdir(directory):
    print('目录存在')
else:
    print('目录不存在')
4. 遍历目录并打印文件
import os

for root, dirs, files in os.walk('.'):
    for file in files:
        print(os.path.join(root, file))
5. 复制目录结构
import os

source_dir = 'source_dir'
target_dir = 'target_dir'

def copy_directory_structure(source, target):
    if not os.path.exists(target):
        os.makedirs(target)
    for item in os.listdir(source):
        s = os.path.join(source, item)
        t = os.path.join(target, item)
        if os.path.isdir(s):
            copy_directory_structure(s, t)

copy_directory_structure(source_dir, target_dir)
6. 重命名目录
import os

old_name = 'old_name'
new_name = 'new_name'

if os.path.exists(old_name) and os.path.isdir(old_name):
    os.rename(old_name, new_name)
    print(f'目录 {old_name} 重命名为 {new_name} 成功!')
else:
    print(f'目录 {old_name} 不存在!')
7. 批量删除指定类型的文件
import os

data_dir = 'data_dir'

for root, dirs, files in os.walk(data_dir):
    for file in files:
        if file.endswith('.tmp'):
            file_path = os.path.join(root, file)
            os.remove(file_path)
            print(f'删除文件: {file_path}')
8. 统计目录下文件数量和总大小
import os

stats_dir = 'stats_dir'
file_count = 0
total_size = 0

for root, dirs, files in os.walk(stats_dir):
    for file in files:
        file_path = os.path.join(root, file)
        file_count += 1
        total_size += os.path.getsize(file_path)

print(f'文件数量: {file_count}')
print(f'总大小: {total_size} 字节')
9. 按日期分类移动文件
import os
import shutil

unsorted_dir = 'unsorted_dir'

for file in os.listdir(unsorted_dir):
    if os.path.isfile(os.path.join(unsorted_dir, file)):
        try:
            date_str = file.split('_')[0]
            date_dir = os.path.join(unsorted_dir, date_str)
            if not os.path.exists(date_dir):
                os.makedirs(date_dir)
            source_file = os.path.join(unsorted_dir, file)
            target_file = os.path.join(date_dir, file)
            shutil.move(source_file, target_file)
            print(f'移动文件 {file}{date_dir}')
        except IndexError:
            print(f'文件名 {file} 不包含日期信息,跳过!')

文件操作和目录同时练习

初级难度

1. 创建目录并写入文件

编写一个 Python 程序,首先创建一个名为 my_project 的新目录。然后在该目录下创建一个名为 readme.txt 的文件,并向其中写入文本 “This is a sample project.”。

import os

# 请在此处编写代码
2. 读取指定目录下文件内容

给定一个目录路径(假设为 test_folder),编写程序检查该目录是否存在。如果存在,读取该目录下名为 data.txt 的文件内容并打印出来;若文件或目录不存在,给出相应提示。

import os

# 请在此处编写代码
3. 删除目录下指定文件

有一个目录 temp_files,编写程序删除该目录下所有扩展名为 .bak 的文件。若目录不存在,输出错误信息。

import os

# 请在此处编写代码

中级难度

4. 遍历目录并统计文件数量和大小

编写一个程序,遍历指定目录(如 project_files)及其所有子目录,统计其中文件的总数和所有文件的总大小(以字节为单位),并将结果输出。同时,要忽略隐藏文件(文件名以 . 开头的文件)。

import os

# 请在此处编写代码
5. 复制目录及其内容

编写一个 Python 程序,将一个源目录(如 source_folder)及其所有子目录和文件复制到目标目录(如 destination_folder)。如果目标目录已存在,先清空它;若不存在,则创建它。

import os
import shutil

# 请在此处编写代码
6. 按文件类型分类整理目录

假设在一个目录 mixed_files 中有各种类型的文件(如 .txt, .jpg, .pdf 等)。编写程序将这些文件按文件类型分类,在该目录下创建以文件扩展名命名的子目录(如 txt, jpg, pdf),并将相应类型的文件移动到对应的子目录中。

import os
import shutil

# 请在此处编写代码

高级难度

7. 备份指定目录并压缩

编写一个 Python 程序,对指定目录(如 important_data)进行备份。将该目录及其所有内容复制到一个以当前日期命名的新目录(如 backup_20250307),然后使用 zipfile 模块将备份目录压缩成一个 ZIP 文件(如 backup_20250307.zip),最后删除备份目录。

import os
import shutil
import zipfile
from datetime import datetime

# 请在此处编写代码
8. 递归清理空目录

编写一个递归函数,清理指定目录(如 large_directory)及其子目录下的所有空目录。如果某个目录下的所有子目录都为空且该目录本身也为空,则将其删除。

import os

# 请在此处编写代码
9. 分析目录结构并生成报告

编写一个程序,分析指定目录(如 complex_project)的结构,统计每个子目录下的文件数量和不同文件类型的分布情况。将分析结果以易读的格式写入一个名为 structure_report.txt 的文件中。

import os

# 请在此处编写代码

参考答案示例

1. 创建目录并写入文件
import os

# 创建目录
dir_name = 'my_project'
if not os.path.exists(dir_name):
    os.mkdir(dir_name)

# 写入文件
file_path = os.path.join(dir_name, 'readme.txt')
with open(file_path, 'w') as f:
    f.write('This is a sample project.')
2. 读取指定目录下文件内容
import os

dir_path = 'test_folder'
file_name = 'data.txt'
file_path = os.path.join(dir_path, file_name)

if os.path.exists(dir_path):
    if os.path.exists(file_path):
        with open(file_path, 'r') as f:
            content = f.read()
            print(content)
    else:
        print(f"文件 {file_name} 不存在于 {dir_path} 中。")
else:
    print(f"目录 {dir_path} 不存在。")
3. 删除目录下指定文件
import os

dir_path = 'temp_files'
if os.path.exists(dir_path):
    for file in os.listdir(dir_path):
        if file.endswith('.bak'):
            file_path = os.path.join(dir_path, file)
            os.remove(file_path)
else:
    print(f"目录 {dir_path} 不存在。")
4. 遍历目录并统计文件数量和大小
import os

dir_path = 'project_files'
file_count = 0
total_size = 0

for root, dirs, files in os.walk(dir_path):
    for file in files:
        if not file.startswith('.'):
            file_path = os.path.join(root, file)
            file_count += 1
            total_size += os.path.getsize(file_path)

print(f"文件总数: {file_count}")
print(f"总大小: {total_size} 字节")
5. 复制目录及其内容
import os
import shutil

source_dir = 'source_folder'
destination_dir = 'destination_folder'

if os.path.exists(destination_dir):
    shutil.rmtree(destination_dir)

shutil.copytree(source_dir, destination_dir)
6. 按文件类型分类整理目录
import os
import shutil

mixed_dir = 'mixed_files'
for file in os.listdir(mixed_dir):
    file_path = os.path.join(mixed_dir, file)
    if os.path.isfile(file_path):
        file_ext = os.path.splitext(file)[1][1:]
        ext_dir = os.path.join(mixed_dir, file_ext)
        if not os.path.exists(ext_dir):
            os.mkdir(ext_dir)
        shutil.move(file_path, os.path.join(ext_dir, file))
7. 备份指定目录并压缩
import os
import shutil
import zipfile
from datetime import datetime

source_dir = 'important_data'
date_str = datetime.now().strftime("%Y%m%d")
backup_dir = f'backup_{date_str}'

# 复制目录
shutil.copytree(source_dir, backup_dir)

# 压缩备份目录
with zipfile.ZipFile(f'{backup_dir}.zip', 'w', zipfile.ZIP_DEFLATED) as zipf:
    for root, dirs, files in os.walk(backup_dir):
        for file in files:
            file_path = os.path.join(root, file)
            zipf.write(file_path, os.path.relpath(file_path, backup_dir))

# 删除备份目录
shutil.rmtree(backup_dir)
8. 递归清理空目录
import os

def remove_empty_directories(dir_path):
    for root, dirs, files in os.walk(dir_path, topdown=False):
        for directory in dirs:
            dir_full_path = os.path.join(root, directory)
            if not os.listdir(dir_full_path):
                os.rmdir(dir_full_path)

dir_to_clean = 'large_directory'
remove_empty_directories(dir_to_clean)
9. 分析目录结构并生成报告
import os

project_dir = 'complex_project'
report_file = 'structure_report.txt'

with open(report_file, 'w') as f:
    for root, dirs, files in os.walk(project_dir):
        file_count = len(files)
        file_type_count = {}
        for file in files:
            file_ext = os.path.splitext(file)[1]
            if file_ext in file_type_count:
                file_type_count[file_ext] += 1
            else:
                file_type_count[file_ext] = 1

        f.write(f"目录: {root}\n")
        f.write(f"  文件数量: {file_count}\n")
        f.write("  文件类型分布:\n")
        for ext, count in file_type_count.items():
            f.write(f"    {ext}: {count} 个\n")
        f.write("\n")

相关文章:

  • 登录校验会话技术
  • 01 微服务与 Spring Cloud 就是从“大杂烩”到“精密协作”的架构演进的必然结果
  • 数据结构:python实现最大堆算法
  • 联核科技AGV无人叉车的应用场景有哪些?
  • 3D数字化:家居行业转型升级的关键驱动力
  • 【电赛推荐芯片】差分放大器:INA143,仪表放大器:INA128 INA333 PGA204
  • 在WSL2-Ubuntu中安装CUDA12.8、cuDNN、Anaconda、Pytorch并验证安装
  • thrift软件、.thrif文件和thrift协议是什么关系,有什么用
  • TensorFlow.js 全面解析:在浏览器中构建机器学习应用
  • 无人机扩频技术对比!
  • 美团校招实习笔试历年真题与内推
  • Facebook 隐私保护技术的发展与未来趋势
  • 记录片《遇见大连》
  • 计算机毕业设计SpringBoot+Vue.js爱心捐赠项目推荐系统 慈善大数据(源码+文档+PPT+讲解)
  • 自然语言处理:高斯混合模型
  • AI编程工具-(六)
  • 【RAG 篇】万字长文:向量数据库选型指南 —— Milvus 与 FAISS/Pinecone/Weaviate 等工具深度对比
  • Linux系统增加用户用于深度学习
  • java错题总结
  • 小程序事件系统 —— 32 事件系统 - 事件分类以及阻止事件冒泡
  • 雄安免费网站建设方案/北京网站推广公司
  • 做快递网站制作/网站优化靠谱seo
  • 新浪云服务器做网站/软文是什么意思?
  • 网站用axure做的rp格式/网站推广平台搭建
  • 同方云罐网站设计/南宁做网站公司
  • 临清建网站/营销和运营的区别是什么