pathlib

os.mkdir() <-> Path.mkdir()
os.makedirs() <-> Path.mkdir()
os.path.exists() <-> Path.exists()
os.listdir() <-> Path.iterdir()
os.path.isdir() <-> Path.is_dir()
os.path.isfile() <-> Path.is_file()
os.path.join() <-> PurePath.joinpath()
os.path.dirname() <-> PurePath.parent

在这里,from pathlib import Path,Path(file_path)会返回一个PosixPath类型的值,例如PosixPath('/Users/xx/Downloads/test_path_lib_folder'))。如何判读数据类型:isinstance(obj_to_test, str)或者使用type(),if type(obj) == str: print('It is a string') else: print('It is not a string.')

使用pathlib连接两个字符串:
path_2 = Path("home", "test", "test.txt")
或者
path_2 = Path("home") / "test" / "test.txt"
或者
p = pathlib.PurePath('/src/goo') p.joinpath('scripts', 'main.py')
或者
p = Path('/src/goo') p.joinpath('scripts', 'main.py')

使用path创建文件夹
pathlib.Path('/tmp/sub1/sub2').mkdir(parents=True, exist_ok=True)

cv2使用Path路径,需要转换为str()
img=cv2.imread(str(f))

folder delete使用shutil更方便

列出所有文件:Path(folder).iterdir()

列出固定文件名:list(Path(folder_name).glob('**/*.jpg'))或者glob.glob(str(Path(folder_name, '*.jpg')))

参考:
[1] https://docs.python.org/3/library/pathlib.html#correspondence-to-tools-in-the-os-module
[2] https://stackoverflow.com/questions/1303243/how-to-find-out-if-a-python-object-is-a-string
[3] https://www.tutorialspoint.com/How-to-check-if-type-of-a-variable-is-string-in-Python
[4] https://www.freecodecamp.org/news/how-to-use-pathlib-module-in-python/
[5] https://stackoverflow.com/questions/67112343/pathlib-vs-os-path-join-in-python
[6] https://stackoverflow.com/questions/50110800/python-pathlib-make-directories-if-they-don-t-exist
[7] https://stackoverflow.com/questions/47990952/typeerror-bad-argument-type-for-built-in-operation
[8] https://docs.python.org/3/library/pathlib.html#correspondence-to-tools-in-the-os-module
[9] https://stackoverflow.com/questions/6996603/how-can-i-delete-a-file-or-folder-in-python
[10] https://www.jquery-az.com/python-delete-file-directory-os-pathlib-shutil/
[11] https://stackoverflow.com/questions/39909655/listing-of-all-files-in-directory
[12] https://docs.python.org/3/library/glob.html
[13] https://stackoverflow.com/questions/14798220/how-can-i-search-sub-folders-using-glob-glob-module

posted @ 2023-05-09 11:11  xiaoxuxli  阅读(68)  评论(0编辑  收藏  举报