os模块的常用函数

#os模块与操作系统相关的一个模块
import os
'''os.system('notepad.exe')
os.system('calc.exe')'''
 
 
os.startfile('C:\\Program Files (x86)\\Tencent\\QQ\\Bin')



os 模块是 Python 中用于与操作系统交互的标准库之一,它提供了很多有用的函数,用于文件和目录操作、进程管理等。以下是一些常用的 os 模块函数:

os.getcwd():

功能:获取当前工作目录。
例子:current_directory = os.getcwd()
os.chdir(path):

功能:改变当前工作目录到指定的路径。
例子:os.chdir("/path/to/directory")
os.listdir(path='.'):

功能:返回指定目录下的所有文件和目录的列表。
例子:files_and_dirs = os.listdir("/path/to/directory")
os.mkdir(path) / os.makedirs(path):

功能:创建单层/多层目录。
例子:os.mkdir("/path/to/new_directory") 或 os.makedirs("/path/to/new/directory")
os.remove(path) / os.unlink(path):

功能:删除文件。
例子:os.remove("/path/to/file.txt")
os.rmdir(path) / os.removedirs(path):

功能:删除单层/多层空目录。
例子:os.rmdir("/path/to/empty_directory") 或 os.removedirs("/path/to/empty/directory")
os.rename(src, dst):

功能:重命名文件或目录。
例子:os.rename("/path/to/old_name.txt", "/path/to/new_name.txt")
os.path.join(path1, path2, ...):

功能:将多个路径组合成一个路径。
例子:full_path = os.path.join("/path/to", "directory", "file.txt")
os.path.exists(path):

功能:检查路径是否存在。
例子:if os.path.exists("/path/to/file.txt"): ...
os.path.isdir(path) / os.path.isfile(path):

功能:检查路径是否为目录/文件。
例子:if os.path.isdir("/path/to/directory"): ...
os.path.abspath(path):

功能:返回规范化的绝对路径。
例子:absolute_path = os.path.abspath("relative/path/to/file.txt")
os.system(command):

功能:在子shell中执行系统命令。
例子:os.system("ls -l")

posted @ 2024-01-14 10:37  YE-  阅读(13)  评论(0编辑  收藏  举报