标准库,os

1.1. 文件和目录操作
获取当前工作目录:

import os
current_directory = os.getcwd()
print(current_directory)

改变当前工作目录:

os.chdir('/path/to/new/directory')

列出目录内容:

files_and_directories = os.listdir('/path/to/directory')
print(files_and_directories)

创建目录

单级目录:
os.mkdir('/path/to/new/directory')
多级目录:
os.makedirs('/path/to/new/directory/level1/level2')

删除目录

单级目录:
os.rmdir('/path/to/directory')
多级目录:
os.removedirs('/path/to/directory/level1/level2')

删除文件

os.remove('/path/to/file')

重命名文件或目录

os.rename('/path/to/oldname', '/path/to/newname')

1.2. 文件属性和权限
检查文件或目录是否存在:

if os.path.exists('/path/to/file'):
    print("File exists")

检查路径是否为文件:

if os.path.isfile('/path/to/file'):
    print("It's a file")
  1. 路径操作
    拼接路径:
path = os.path.join('/path/to', 'directory', 'file.txt')
print(path)
posted @ 2025-06-05 15:14  呆呆酱  阅读(8)  评论(0)    收藏  举报