当前位置:首页>python>Python文件与文件夹操作

Python文件与文件夹操作

  • 2026-08-22 09:00:57
Python文件与文件夹操作

一、文件基础操作

1. 打开文件 - open()函数

# 基本语法file = open(filename, mode, encoding)# mode参数说明# 'r'  - 只读模式(默认)# 'w'  - 写入模式(会覆盖原文件)# 'a'  - 追加模式# 'x'  - 独占创建模式(文件存在则报错)# 'b'  - 二进制模式,如 'rb', 'wb'# 't'  - 文本模式(默认)# '+'  - 读写模式,如 'r+', 'w+'

2. 读取文件内容

# 方法1:使用with语句(推荐)with open('example.txt', 'r', encoding='utf-8') as file:    content = file.read()  # 读取全部内容    print(content)# 方法2:逐行读取with open('example.txt', 'r', encoding='utf-8') as file:for line in file:        print(line.strip())  # strip()去掉换行符# 方法3:读取多行with open('example.txt', 'r', encoding='utf-8') as file:    lines = file.readlines()  # 返回包含所有行的列表for line in lines:        print(line.strip())# 方法4:读取指定字节数with open('example.txt', 'r', encoding='utf-8') as file:    first_100 = file.read(100)  # 读取前100个字符

3. 写入文件内容

# 写入文件(覆盖模式)with open('output.txt', 'w', encoding='utf-8') as file:    file.write("第一行内容\n")    file.write("第二行内容\n")# 追加内容with open('output.txt', 'a', encoding='utf-8') as file:    file.write("追加的内容\n")# 写入多行lines = ["第一行\n", "第二行\n", "第三行\n"]with open('output.txt', 'w', encoding='utf-8') as file:    file.writelines(lines)

4. 文件指针操作

with open('example.txt', 'r+', encoding='utf-8') as file:# 获取当前指针位置    position = file.tell()    print(f"当前指针位置: {position}")# 移动指针    file.seek(10)  # 移动到第10个字节    content = file.read(5)  # 读取5个字符    print(content)# 移动到文件末尾    file.seek(0, 2)  # 0表示偏移量,2表示从文件末尾开始

5. 检查文件状态

import os# 检查文件是否存在if os.path.exists('example.txt'):    print("文件存在")# 获取文件大小size = os.path.getsize('example.txt')print(f"文件大小: {size} 字节")# 获取文件修改时间import timemtime = os.path.getmtime('example.txt')print(f"修改时间: {time.ctime(mtime)}")

二、文件夹(目录)基础操作

1. 导入os模块

import osimport shutil  # 用于高级文件操作

2. 创建和删除目录

# 创建单个目录os.mkdir('new_folder')# 创建多级目录os.makedirs('folder1/folder2/folder3')# 删除空目录os.rmdir('empty_folder')# 删除目录及其所有内容(危险!)shutil.rmtree('folder_with_content')# 安全删除(先检查)folder_path = 'to_delete'if os.path.exists(folder_path) and os.path.isdir(folder_path):    shutil.rmtree(folder_path)

3. 遍历目录

# 列出目录下的所有文件和文件夹items = os.listdir('.')for item in items:    print(item)# 使用os.scandir()(推荐,性能更好)with os.scandir('.') as entries:for entry in entries:if entry.is_file():            print(f"文件: {entry.name}")elif entry.is_dir():            print(f"目录: {entry.name}")# 遍历所有子目录(递归)for root, dirs, files in os.walk('.'):    print(f"当前目录: {root}")    print(f"子目录: {dirs}")    print(f"文件: {files}")    print("-" * 50)

4. 路径操作

import os# 获取当前工作目录current_dir = os.getcwd()print(f"当前目录: {current_dir}")# 改变工作目录os.chdir('../')# 路径拼接(推荐使用os.path.join)path = os.path.join('folder1', 'folder2', 'file.txt')print(f"拼接后的路径: {path}")# 获取绝对路径abs_path = os.path.abspath('example.txt')print(f"绝对路径: {abs_path}")# 路径分解dir_name, file_name = os.path.split('/path/to/file.txt')print(f"目录部分: {dir_name}")print(f"文件名部分: {file_name}")# 获取文件名和扩展名name, ext = os.path.splitext('document.txt')print(f"文件名: {name}")print(f"扩展名: {ext}")

5. 检查路径类型

path = 'example.txt'# 检查是否为文件if os.path.isfile(path):    print(f"{path} 是一个文件")# 检查是否为目录if os.path.isdir(path):    print(f"{path} 是一个目录")# 检查是否为链接if os.path.islink(path):    print(f"{path} 是一个链接")

三、实用示例

示例1:复制文件

import shutil# 复制文件shutil.copy('source.txt', 'destination.txt')# 复制文件并保留元数据shutil.copy2('source.txt', 'destination.txt')# 复制整个目录shutil.copytree('source_dir', 'destination_dir')

示例2:移动/重命名文件

import os# 重命名文件os.rename('old_name.txt', 'new_name.txt')# 移动文件(到不同目录)os.rename('file.txt', 'new_folder/file.txt')# 使用shutil.move(更强大)shutil.move('source.txt', 'destination_folder/')

示例3:批量处理文件

import os# 批量重命名文件folder = 'images'counter = 1for filename in os.listdir(folder):if filename.endswith('.jpg'):        new_name = f'image_{counter:03d}.jpg'        old_path = os.path.join(folder, filename)        new_path = os.path.join(folder, new_name)        os.rename(old_path, new_path)        counter += 1

示例4:查找特定文件

import osdeffind_files(extension, search_path='.'):"""查找指定扩展名的文件"""    results = []for root, dirs, files in os.walk(search_path):for file in files:if file.endswith(extension):                results.append(os.path.join(root, file))return results# 查找所有.py文件python_files = find_files('.py')for file in python_files:    print(file)

示例5:文件备份工具

import osimport shutilimport datetimedefbackup_file(source_file, backup_dir='backups'):"""备份文件到指定目录"""# 创建备份目录ifnot os.path.exists(backup_dir):        os.makedirs(backup_dir)# 生成带时间戳的备份文件名    timestamp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')    filename = os.path.basename(source_file)    name, ext = os.path.splitext(filename)    backup_name = f"{name}_{timestamp}{ext}"    backup_path = os.path.join(backup_dir, backup_name)# 复制文件    shutil.copy2(source_file, backup_path)    print(f"已备份: {source_file} -> {backup_path}")return backup_path# 使用示例backup_file('important_document.txt')

最新文章

随机文章