设计师a 网站免费b2b网站推广渠道
os 库是Python中用于与操作系统进行交互的标准库,以下是一些 os 库的常用示例:
获取当前工作目录
python
import os
current_dir = os.getcwd()
print(current_dir)
os.getcwd() 函数用于获取当前工作目录的路径。
列出目录内容
python
import os
dir_contents = os.listdir('.')
for item in dir_contents:
print(item)
os.listdir() 函数用于列出指定目录中的所有文件和文件夹,参数为指定目录的路径,使用 '.' 表示当前目录。
创建目录
python
import os
new_dir = 'new_folder'
if not os.path.exists(new_dir):
os.mkdir(new_dir)
os.mkdir() 函数用于创建新目录,如果目录已存在,会抛出异常,因此先使用 os.path.exists() 检查目录是否存在。
删除目录
python
import os
dir_to_remove = 'new_folder'
if os.path.exists(dir_to_remove):
os.rmdir(dir_to_remove)
os.rmdir() 函数用于删除空目录,如果目录不为空,会抛出异常。
重命名文件或目录
python
import os
old_name = 'old_file.txt'
new_name = 'new_file.txt'
if os.path.exists(old_name):
os.rename(old_name, new_name)
os.rename() 函数用于重命名文件或目录,如果目标名称已存在,会抛出异常。
执行系统命令
python
import os
os.system('dir') # 在Windows系统中列出目录内容,在Linux中使用ls
os.system() 函数用于执行系统命令,并返回命令执行的返回值,返回值为0表示命令执行成功,非0表示失败。