python 文件与path路径模块详解
2024年6月6日大约 2 分钟约 715 字
模块介绍
pathlib
: 面向对象的文件系统路径操作方式,适合用于路径的构建、解析和修改,特别是在处理文件和目录的创建、读取和写入操作。os
: 封装了操作系统的文件系统操作,适合于需要直接与操作系统层面交互的操作,提供了一系列函数用于创建、删除文件和目录,获取文件属性,执行系统命令等。shutil
: 提供了高级的文件和目录操作,适合用于文件管理任务,包括大规模文件复制、移动、删除、压缩和解压缩等。
路径操作
import os
from pathlib import Path
home_path: Path = Path.home() # 用户家目录
dir_path: Path = Path.cwd() # 当前环境的工作目录
file_path = Path(__file__) # 当前文件路径
dir_path = file_path.parent # 获取文件目录
filename: str = file_path.name # 获取文件名称
dir_name: str = file_path.parent.name # 获取当前目录名称
file_suffix: str = file_path.suffix # 获取文件扩展名
file_suffixs: list = file_path.suffixes # 获取文件多个扩展名(假如存在)
# 路径添加
new_file_path = dir_path / 'new_file.txt'
# 修改路径权限
file_path.chmod(0o444)
# 修改路径的文件名称
file_path.with_name('abc.txt')
# 修改路径的文件扩展名
file_path.with_suffix('.py')
# 将路径绝对化
file_path.resolve()
file_path.absolute()
# 创建Path对象
path = Path('/new/path')
# 切换工作目录路径(切换到path路径下)
os.chdir(path)
# 路径判断
Path('/a/b/c.py').match('b/*.py')
path.exists()
path.is_dir()
path.is_file()
# 列出目录内容(不传路径默认为当前路径)
dir_list = [p for p in path.iterdir()]
# 创建目录(父目录不存在则自动创建,目录已经存在不抛出异常)
dir_path.mkdir(parents=True, exist_ok=True)
# 创建文件
file_path.touch(mode=0o666, exist_ok=True)
# 删除文件
path = Path('/path/to/file.txt')
path.unlink()
# 删除目录(目录必须是空的)
dir_path.rmdir()
# 重命名文件或目录
old_file = Path('/path/to/old_name.txt')
new_file = Path('/path/to/new_name.txt')
old_file.rename(new_file)
# 执行系统命令
os.system('echo hello')
当前工作目录(Current Working Directory,简称 CWD)
在操作系统中,任何正在运行的进程所在的目录。这是一个基本的概念,用于定义相对文件路径的基点。当你在命令行或脚本中打开、保存、或访问文件时,如果没有指定完整路径,系统会默认在当前工作目录下查找这些文件。
环境变量
import os
os.environ.get('PATH') # 获取环境变量PATH的值
os.environ['NEW_VAR'] = 'value' # 设置新的环境变量NEW_VAR
del os.environ['NEW_VAR'] # 删除环境变量
文件操作
from pathlib import Path
# 读取文件
with Path('/example/directory/file.txt').open('r') as file:
contents = file.read()
content = file_path.read_text()
content = file_path.read_bytes()
# 写入文件
with file_path.open('w') as file:
file.write('Hello, world!')
file_path.write_text('Hello, world!') # 清空文件并写入文本
file_path.write_bytes(b'Hello, world!') # 清空文件并写入二进制数据