1. 获取当前工作目录
import os
# 获取当前工作目录
current_dir = os.getcwd()
print(f"当前工作目录: {current_dir}")
掌握文件和目录操作的核心技能
Python的os
模块提供了与操作系统交互的各种功能,包括:
使用前需要导入:import os
import os
# 获取当前工作目录
current_dir = os.getcwd()
print(f"当前工作目录: {current_dir}")
# 创建单个目录
os.mkdir("new_directory")
# 创建多级目录
os.makedirs("parent/child/grandchild", exist_ok=True)
# 删除文件
os.remove("unwanted_file.txt")
# 删除空目录
os.rmdir("empty_directory")
# 删除目录及其内容
import shutil
shutil.rmtree("directory_with_content")
# 安全地拼接路径
path = os.path.join("folder", "subfolder", "file.txt")
print(f"完整路径: {path}")
# 拆分路径
dirname, filename = os.path.split("/path/to/file.txt")
print(f"目录: {dirname}, 文件名: {filename}")
# 获取文件扩展名
filename, extension = os.path.splitext("document.pdf")
print(f"文件名: {filename}, 扩展名: {extension}")
# 遍历目录内容
for item in os.listdir("."):
print(item)
# 使用os.walk遍历目录树
for root, dirs, files in os.walk("project"):
print(f"当前目录: {root}")
print(f"包含子目录: {dirs}")
print(f"包含文件: {files}")
print("-" * 50)
# 操作系统名称
print(f"操作系统: {os.name}")
# 环境变量
print(f"PATH环境变量: {os.getenv('PATH')}")
# 当前用户名
print(f"用户名: {os.getlogin()}")
# 执行系统命令
os.system("dir") # Windows
os.system("ls") # Linux/Mac
# 获取命令输出
output = os.popen("python --version").read()
print(f"Python版本: {output}")
函数 | 描述 |
---|---|
os.rename(src, dst) |
重命名文件或目录 |
os.path.exists(path) |
检查路径是否存在 |
os.path.isdir(path) |
检查是否为目录 |
os.path.isfile(path) |
检查是否为文件 |
os.path.getsize(path) |
获取文件大小(字节) |
os.path.abspath(path) |
获取绝对路径 |
os.chdir(path) |
改变当前工作目录 |
os.path.join()
替代手动拼接路径,确保跨平台兼容性os.makedirs()
时设置exist_ok=True
可避免目录已存在时的错误os.walk()
遍历大型目录时注意性能问题os.path
模块的函数进行路径操作更安全可靠本文由LiangMi于2025-07-17发表在吾爱品聚,如有疑问,请联系我们。
本文链接:https://pjw.521pj.cn/20255806.html
发表评论