Python 文件操作指南
基本文件读写
读取和写入文件的基础操作。
def read_file_content(filename):
with open(filename, 'r', encoding='utf-8') as file:
content = file.read()
return content
def write_to_file(filename, content):
with open(filename, 'w', encoding='utf-8') as file:
file.write(content)
def append_to_file(filename, content):
with open(filename, 'a', encoding='utf-8') as file:
file.write(content)
文件读取模式
按不同方式读取文件内容。
def read_file_by_lines(filename):
with open(filename, 'r', encoding='utf-8') as file:
for line in file:
yield line.strip()
def read_file_chunk(filename, chunk_size=1024):
with open(filename, 'rb') as file:
while True:
chunk = file.read(chunk_size)
if not chunk:
break
yield chunk
文件指针操作
控制文件读写位置。
def modify_file_content(filename):
with open(filename, 'r+', encoding='utf-8') as file:
file.seek(0)
content = file.read()
file.seek(0)
file.write(content.upper())
file.truncate()
文件路径处理
使用 os 模块处理文件路径。
import os
def process_directory(directory_path):
if not os.path.exists(directory_path):
os.makedirs(directory_path)
file_path = os.path.join(directory_path, "sumingcheng.txt")
return os.path.abspath(file_path)
文件复制与移动
使用 shutil 模块操作文件。
import shutil
def backup_file(source_path, backup_dir):
if not os.path.exists(backup_dir):
os.makedirs(backup_dir)
backup_path = os.path.join(backup_dir,
f"{os.path.basename(source_path)}.bak")
shutil.copy2(source_path, backup_path)
return backup_path
目录遍历实现
遍历目录中的文件和子目录。
def scan_directory(directory_path):
results = {
"files": [],
"directories": [],
"total_size": 0
}
for root, dirs, files in os.walk(directory_path):
for name in files:
file_path = os.path.join(root, name)
results["files"].append(file_path)
results["total_size"] += os.path.getsize(file_path)
for name in dirs:
dir_path = os.path.join(root, name)
results["directories"].append(dir_path)
return results
文件监控
监控文件变化。
import time
def monitor_file_changes(filename, interval=1):
last_mtime = os.path.getmtime(filename)
while True:
current_mtime = os.path.getmtime(filename)
if current_mtime != last_mtime:
yield "File modified"
last_mtime = current_mtime
time.sleep(interval)
安全文件操作
处理文件操作中的异常情况。
def safe_file_operation(filename, operation):
try:
with open(filename, encoding='utf-8') as file:
return operation(file)
except FileNotFoundError:
return "文件不存在"
except PermissionError:
return "没有操作权限"
except Exception as error:
return f"操作失败{str(error)}"