Python file/path handling records

1. Basic operation

1.1 Create a new folder

os.mkdir(path)You can only create a new folder under an existing path. If
os.makedirs(path, mode=511, exist_ok=False) the parent directory of the folder does not exist, it will be created together. If the path of the new folder already exists, an error will be reported. If exist_ok is set to True, no error will be reported.

Note: Only folders can be created, for example, os.mkdir(‘a.txt’)it is also a folder of a.txt instead of a txt file

1.2 Copy

shutil.copyfile(oldpath, newpath)

1.3 delete

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

1.4 Move/Rename

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

2. Attribute judgment

2.1 Existence

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

2.2 Is it a folder

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

2.3 Whether it is a file

os.path.isfile(path)

3. Get information

3.1 Current operating system path separator

os.sep

3.2 The absolute path of the current working directory

os.getcwd()

3.3 Parent directory

os.path.dirname(path)

3.4 All subfilenames

os.listdir(path)

3.5 Suffix condition sub-file path

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 Current operating system type

os.name

Windows corresponds to nt
Linux corresponds to posix

3.7 Path prefixes and suffixes

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 Path filename

os.path.basename(path)

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

4. Custom functions

4.1 Empty Folder

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)

Guess you like

Origin blog.csdn.net/weixin_43605641/article/details/117790138