python库介绍-os库
os
是 Python 的一个标准库,提供了许多与操作系统交互的函数。模块提供了很多实用的功能,可以帮助你在 Python 程序中进行文件和目录操作,以及管理文件系统。以下是一些常见的 os
模块功能及其用法示例:
1. os.path
-
os.path.join(path1, path2, ...)
:将多个路径组合成一个完整路径。import os path = os.path.join('/path/to', 'directory', 'file.txt')
-
os.path.exists(path)
:检查指定路径是否存在。if os.path.exists('/path/to/file.txt'): print("File exists")
-
os.path.isdir(path)
和os.path.isfile(path)
:判断路径是指向目录还是文件。if os.path.isdir('/path/to/directory'): print("This is a directory")
-
os.path.basename(path)
:获取路径中的文件名或目录名。file_name = os.path.basename('/path/to/file.txt')
2. 文件和目录操作
-
os.listdir(directory)
:列出目录中的内容。files = os.listdir('/path/to/directory')
-
os.mkdir(path)/os.makerdirs(path)
:创建目录。os.mkdir('/path/to/new_directory')
-
os.remove(path)
:删除文件。os.remove('/path/to/file.txt')
-
os.rmdir(directory)
:删除空目录。os.rmdir('/path/to/directory')
3. 其他常用功能
-
os.getcwd()
:获取当前工作目录。current_dir = os.getcwd()
-
os.chdir(path)
:改变当前工作目录。os.chdir('/new/path')
-
os.rename(src, dst)
:重命名文件或目录。os.rename('/path/to/old_file.txt', '/path/to/new_file.txt')
注意事项
- 使用
os
模块时需要注意跨平台兼容性,某些功能可能在不同操作系统上表现不同。 - 确保有足够的权限执行文件和目录操作,避免意外删除或修改重要文件。