Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use pathlib to replace os.path with python3

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces "how python3 uses pathlib instead of os.path". In daily operation, I believe many people have doubts about how python3 uses pathlib instead of os.path. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts of "how python3 uses pathlib instead of os.path". Next, please follow the editor to study!

Preface

If you're still worried about manipulating file paths and don't know how to use the os.path module, it's time to try pathlib.

Pathlib library

The pathlib library has matured from python3.4 to python3.6. If you can directly use more than 3.6 for your new project, pathlib is recommended. There are several advantages over the old os.path:

The old path operation functions are confused, some are imported into os, some are in os.path, while the new usage can be managed by pathlib.

The old usage is very difficult to deal with different operating systems win,mac and linux. When you change the operating system, you often have to change the code and often do some extra operations.

The old usage is mainly in the form of functions, and the data type returned is usually a string. However, paths and strings are not equivalent, so other class libraries are often introduced to assist operations when using os operation paths. The new usage is object-oriented, which is more flexible and convenient to deal with.

Pathlib simplifies a lot of operations and is easier to use.

Commonly used pathlib and os comparison diagrams

Operation os and os.pathpathlib absolute path os.path.abspathPath.resolve modify permissions os.chmodPath.chmod create directory os.mkdirPath.mkdir rename os.renamePath.rename Mobile os.replacePath.replace delete directory os.rmdirPath.rmdir delete file os.remove Whether os.unlinkPath.unlink working directory os.getcwdPath.cwd exists os.path.existsPath.exists user directory os.path.expanduserPath.expanduser and Path.home is a directory os.path.isdirPath.is_dir is a file os.path.isfilePath.is_file is a connection os.path.islinkPath.is_symlink file attribute os.statPath.stat, Path.owner Whether Path.group is an absolute path os.path.isabsPurePath.is_absolute path stitching os.path.joinPurePath.joinpath file name os.path.basenamePurePath.name parent directory os.path.dirnamePurePath.parent same name file os.path.samefilePath.samefile suffix os.path.splitextPurePath.suffixpathlib get file path Path.cwd get current folder path

It is important to note that instead of returning a string, it is a WindowsPath object

From pathlib import Path# 1. You can directly call the class method .cwd () print (Path.cwd ()) # C:\ Users\ dell\ PycharmProjects\ untitled3\ demo# 2. You can also instantiate and call p = Path ('. /') print (p.cwd ()) # C:\ Users\ dell\ PycharmProjects\ untitled3\ demoprint (type (p.cwd () # get the current file path from pathlib import Path# current file path p = Path (_ _ file__) print (p) get the Path object absolute path from pathlib import Path# current file path p = Path ('data.json') print ( P) # data.json object print (p.absolute ()) # C:\ Users\ dell\ PycharmProjects\ untitled3\ demo\ data.json some commonly used get file attributes from pathlib import Path# current file path p = Path (_ _ file__) print (p.absolute ()) # get absolute path print (p.resolve ()) # get absolute path print (p.name) # get file name 'a1117.py'print (p.stem) # just the file name Do not use the suffix a1117print (p.suffix) # get the file suffix .pyprint (p.suffixes) # all monkeys in the file ['.py'] print (p.parts) # split ('C:\', 'Users',' dell', 'PycharmProjects',' untitled3', 'demo' 'a1117.py') print (p.parent) # C:\ Users\ dell\ PycharmProjects\ untitled3\ demoprint (p.parent.parent) # C:\ Users\ dell\ PycharmProjects\ untitled3print (p.parents) # all parent print (p.anchor) # anchors C:\ or / get the upper layer in front of the directory, and the upper level directory from pathlib import Path#. Parent gets the upper layer print (Path.cwd () .parent) # and calls .parentp = Path ('. /') print (p.cwd (). Parent)

Get the upper layer using the chained method call .parent.parent

From pathlib import Path# .parent gets the upper layer print (Path.cwd () .parent.parent) # instantiates and calls .parentp = Path ('. /') print (p.cwd () .parent.parent) to get the user home directory from pathlib import Pathprint (Path.home ()) # c:\ Users\ dell judgment document Folder is_file () determines whether it is a file from pathlib import Path# 1. Is_file () determines whether it is a file print (Path.cwd (). Is_file ()) # False# 2. You can also instantiate and call p = Path ('. / data.json') print (p.is_file ()) # Trueis_dir () to determine whether it is a folder from pathlib import Path# 1. Is_file () to determine whether it is a file print (Path.cwd (). Is_dir ()) # True# 2. You can also instantiate and call p = Path ('. / data.json') print (p.is_dir ()) # Falseexists () to determine whether a file or folder exists from pathlib import Path# exists () to determine whether there is p = Path ('. / data.json') print (p.exists ()) # True or Falseis_absolute () to determine whether it is an absolute path from pathlib import Path# current file path p = Path ( _ _ file__) print (p) print (p.is_absolute ()) # Truejoinpath splicing directory

You can use a method similar to os.path.join

From pathlib import Path# current file path p = Path ('. /') print (p.absolute ()) # C:\ Users\ dell\ PycharmProjects\ untitled3\ demoprint (p.joinpath ('data.json')) # data.jsonprint (p.joinpath (' data.json'). Absolute ()) # C:\ Users\ dell\ PycharmProjects\ untitled3\ demo\ data.json# splicing multi-layer print (p.joinpath ('files') 'data.json')) # files\ data.jsonprint (p.joinpath (' files', 'data.json'). Absolute ()) # C:\ Users\ dell\ PycharmProjects\ untitled3\ demo\ files\ data.json

Pathlib supports using / stitching paths, and very few people use this syntax estimation.

From pathlib import Path# current file path p = Path ('. /') # / splicing new_path = p / 'files' /' data.json'print (new_path.absolute ()) iterdir () traverses the file directory

For example, there are the following folders and sub-files in the files directory of the current script

.iterdir () traverses all paths (files and subdirectories) under a directory

From pathlib import Path# current file path p = Path ('files') for i in p.iterdir (): print (i.absolute ()) "run result: C:\ Users\ dell\ PycharmProjects\ untitled3\ demo\ files\ jsonC:\ Users\ dell\ PycharmProjects\ untitled3\ demo\ files\ username.txtC:\ Users\ dell\ PycharmProjects\ untitled3\ demo\ files\ yaml"

If you only need to get the folder, you can add a judgment. Is _ dir ()

From pathlib import Path# current file path p = Path ('files') print ([i for i in p.iterdir () if i.is_dir ()]) # [WindowsPath (' files/json'), WindowsPath ('files/yaml')]

You can also get file objects with .is _ file

From pathlib import Path# current file path p = Path ('files') print ([i for i in p.iterdir () if i.is_file ()]) # [WindowsPath (' files/username.txt')] glob () and rglob () pattern match (regular expression)

Matches the specified path using pattern matching (regular expressions). Glob will only match the current directory, and rglob will recursively all subdirectories such as the following folders and sub-files in the files directory of the current script

Glob will only match the current directory from pathlib import Pathp = Path ('files') # glob will only traverse to find the current directory print (p.glob (' * .txt')) # print ([i for i in p.glob ('* .txt')]) # [WindowsPath ('files/username.txt')] print ([i for i in p.glob (' * yml')]) # [] rglob will recursively all subdirectories from pathlib import Pathp = Path ('files') # glob will only traverse to find the current directory print (p.rglob (' * .txt')) # print ([i for i in p.rglob ('* .txt')]) # [WindowsPath ('files/username.txt')] print ([i for i in p.rglob (' * .yml')]) # [WindowsPath ('files/yaml/aa.yml')) WindowsPath ('files/yaml/bb.yml')] match () check whether the path conforms to the rules from pathlib import Pathp = Path (' data.json') # math check matching rules print (p.match ('* .json')) # True create file operation touch () create file from pathlib import Pathp = Path ('xx.json') p.touch () # create a xx.json

P.touch () will not report an error when the file already exists, because if the default parameter exist_ok=True is set to exist_ok=False, touch will report an error if the file already exists

From pathlib import Pathp = Path ('xx.json') p.touch (exist_ok=False) # create a xx.json

Throw an exception FileExistsError: [Errno 17] File exists: 'xx.json'

Mkdir () create a directory

Create a yoyo directory under the current script

From pathlib import Pathp = Path ('yoyo') # mkdir create yoyo directory p.mkdir ()

If you want to create a multi-tier directory 'yoyo/json'' at once

From pathlib import Pathp = Path ('yoyo/json') # mkdir create yoyo/json directory p.mkdir ()

An exception FileNotFoundError: [WinError 3] the system cannot find the specified path. : 'yoyo\ json'

Recursive create directory mkdir (parents=True) from pathlib import Pathp = Path ('yoyo/json') # mkdir create yoyo/json directory p.mkdir (parents=True) delete file operation

Deleting a directory is very dangerous and there is no prompt, so be sure to proceed with caution

Rmdir () deletes only one directory at a time, and the current directory must be empty. From pathlib import Pathp = Path ('yoyo/json') # mkdir create yoyo/json directory p.rmdir () unlink () delete file from pathlib import Pathp = Path (' files/username.txt') p.unlink () file read and write operation

Pathlib simply encapsulates reads and writes, eliminating the need to repeatedly open files and manage file closures.

.read _ text () reads the text

.read _ bytes () reads bytes

.write _ text () writes text

.write _ bytes () writes to tytes

From pathlib import Pathp = Path ('yo.txt') p.write_text ("hello world") print (p.read_text ()) # hello world

The file.write operation uses w mode, which will be overwritten if there is already a file content.

Modify file replace () move file from pathlib import Pathp = Path ('yo.txt') p.write_text ("hello world") print (p.read_text ()) # hello worldp.replace (' xx.json') with_name () rename file from pathlib import Pathp = Path ('hello.txt') p.write_text ("hello world") print (p.read_text ()) # hello world# rename to a new file Object new_file = p.with_name ('x.txt') print (new_file) p.replace (new_file) # move to the new location here The study on "how python3 uses pathlib to replace os.path" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report