Python 文件 / 路径处理记录

1. 基础操作

1.1 新建文件夹

os.mkdir(path) 只能在已存在的路径下新建文件夹
os.makedirs(path, mode=511, exist_ok=False) 文件夹父目录不存在会一起创建,新建文件夹路径已经存在会报错,exist_ok 设为 True 则不报错

注:只能建文件夹,譬如 os.mkdir(‘a.txt’) 也是 a.txt 的文件夹而不是 txt 文件

1.2 复制

shutil.copyfile(oldpath, newpath)

1.3 删除

os.remove(path) 删除文件
os.rmdir(path) 删除空文件夹

1.4 移动 / 重命名

os.rename(oldpath, newpath)
shutil.move(oldpath, newpath)

2. 属性判断

2.1 是否存在

pathlib.Path(path).exists()
os.path.exists(path)

2.2 是否为文件夹

pathlib.Path(path).is_dir()
os.path.isdir(path)

2.3 是否为文件

os.path.isfile(path)

3. 获取信息

3.1 当前操作系统路径分隔符

os.sep

3.2 当前工作目录的绝对路径

os.getcwd()

3.3 父级目录

os.path.dirname(path)

3.4 所有子文件名

os.listdir(path)

3.5 后缀条件子文件路径

pathlib.Path(path).glob(条件)

from pathlib import Path

print(list(Path(root).glob('*')))
print(list(Path(root).glob('*.txt')))
test1: [WindowsPath('dirtest/abc'), WindowsPath('dirtest/def'), WindowsPath('dirtest/g.txt')]
test2: [WindowsPath('dirtest/g.txt')]

3.6 当前操作系统类型

os.name

Windows 对应 nt
Linux 对应 posix

3.7 路径的前缀和后缀

os.path.splitext(path)

img_path = 'D:/learning/Function coordinates/test/p1_1.png'
os.path.splitext(img_path)
('D:/learning/Function coordinates/test/p1_1', '.png')

3.8 路径的文件名

os.path.basename(path)

img_path = 'D:/learning/Function coordinates/test/p1_1.png'
os.path.basename(img_path)
'p1_1.png'

4. 自定义函数

4.1 清空文件夹

import os

def empty_folder(root_path):
    for file in os.listdir(root_path):
        file_path = os.path.join(root_path, file)
        if os.path.isfile(file_path):
            os.remove(file_path)
        else:
            if os.listdir(file_path):
                empty_folder(file_path)
                os.rmdir(file_path)
            else:
                os.rmdir(file_path)

猜你喜欢

转载自blog.csdn.net/weixin_43605641/article/details/117790138