Python pathlib memorandum

What is pathlib

Convenient features in the standard library since Python 3.4 (?) (Official documentation) Not only does it have a lot of alternatives to the os library, it's a great guy.

It's too much work and it's too good, so it's a lot of work to find out (too many features) Therefore, I will quickly describe only how to use Path, which I often use personally. I would love to hear your comments if there is a better way.

Path object preparation

#import
from pathlib import Path

#Object creation
p = Path(r"C:\Users\admin\Desktop\temp\hoge.txt")

How to get various information

#file name
print(path.name) # >> hoge.txt
#File name without extension
print(path.stem) # >> hoge
#Get only the extension
print(path.suffix) # >> .py
#At the beginning.Cut out if you don't need
print(path.suffix.lstrip(".")) # >> py

#Up to the parent hierarchy
print(path.parent) # >> C:\Users\admin\Desktop\temp
#Higher level (\..\..It's okay to combine them, but isn't it? )
print(path.parents[0]) # >> C:\Users\admin\Desktop\temp
print(path.parents[1]) # >> C:\Users\admin\Desktop
print(path.parents[2]) # >> C:\Users\admin

basic operation

# os.path.join()Usage
path = Path("src", "python", "naritoblog")  # src/python/naritoblog

#Join by operator
path1 = Path("src")
path2 = Path("python")
path3 = path1 / path2 / "naritoblog"  # src/python/naritoblog

#Conversion to string
print(type(path3.__str__())) # >> str
#This is fine
print(type(str(path3)))      # >> str

#Convert from relative path to absolute path
path1 = Path("hoge.txt")
print(path1)           # >> hoge.txt
print(path1.resolve()) # >> C:\Users\admin\Desktop\temp\hoge.txt

Get list in folder

path = Path("Taisho")
#Get all
list(path.glob("*"))
#File only
list(path.glob("*.*"))
#Directory only
[list for list in path.iterdir() if list.is_dir()]

Get a list of everything under a specific folder

With the Path object, you don't even need to do complicated recursive processing!

#All of the following
list(path.glob("**/*"))
#The following files
list(path.glob("**/*.*"))
#Extension can be specified
list(path.glob("**/*.txt"))
#Directory only
[list for list in path.glob("**/*") if list.is_dir()]

Text file input / output

Of course, not only .txt but anything text-based.

txt_path = Path("xxx.txt")
#File creation (export)
with txt_path.open("w", encoding="utf-8") as file:
    file.write("Test output")
#Read file
with txt_path.open("r", encoding="utf-8") as file:
    print(file.read())

e? Is it long? Then over here

txt_path.write_text("Description", encoding="utf-8")  #writing
src = txt_path.read_text(encoding="utf-8")  #Read

Create folder

Create a fictitious Path object and create its existence.

make_dir = Path("mkdir")
#parents: Created for each parent directory (mksirs-like)
# exist_ok: Can be created even if there is a folder with the same name (there is no error drop that exists)
make_dir.mkdir(parents=True, exist_ok=True)
# >>A folder called "mkdir" is created in the current directory

Delete files and folders

I don't say remove to delete files. The era is unlink. ~~ Words you want to speak out ~~

#Delete file
a_txt = Path('xxx.txt')
a_txt.unlink()

#Delete directory (only empty)
rm_dir = Path('mkdir')
rm_dir.rmdir()

Change file name / extension

In short, change only the name and suffix attributes of the Path object Note that it is the information of the Path object that changes, not the actual file. If you want to change the actual situation, use ʻos.rename` etc. (Is it possible with pathlib?)

There is also a similar function, .rename (), but it was strangely difficult to use, so I omitted it.

#Rename file (name attribute)
path_a = Path(r"C:\temp\a_text.txt")
path_b = path_a.with_name("b_text.txt")
print(path_a) # >> C:\temp\a_text.txt
print(path_b) # >> C:\temp\b_text.txt

#Change extension (suffix attribute)
path_a = Path(r"C:\temp\wich_test.txt")
path_b = path_a.with_suffix(".csv")
print(path_a) # >> C:\temp\wich_test.txt
print(path_b) # >> C:\temp\wich_test.csv

Conclusion

The official documentation is the most abundant for information related to pathlib

Recommended Posts

Python pathlib memorandum
Python memorandum
Python Memorandum 2
Python memorandum
python memorandum
python memorandum
Python memorandum
python memorandum
Python memorandum
Python basics memorandum
Python memorandum (algorithm)
Python memorandum [links]
Python memorandum numbering variables
python memorandum (sequential update)
Python memorandum (personal bookmark)
Python basic memorandum part 2
New in Python 3.4.0 (1)-pathlib
[Python] Iterative processing_Personal memorandum
Memorandum @ Python OR Seminar
python memorandum super basic
Effective Python Learning Memorandum Day 15 [15/100]
Cisco Memorandum _ Python config input
Python
Effective Python Learning Memorandum Day 6 [6/100]
Effective Python Learning Memorandum Day 12 [12/100]
Effective Python Learning Memorandum Day 9 [9/100]
Effective Python Learning Memorandum Day 8 [8/100]
ABC memorandum [ABC163 C --managementr] (Python)
About python beginner's memorandum function
Memorandum @ Python OR Seminar: matplotlib
[Python] SQLAlchemy error avoidance memorandum
A memorandum about correlation [Python]
Effective Python Learning Memorandum Day 14 [14/100]
Effective Python Learning Memorandum Day 1 [1/100]
Memorandum @ Python OR Seminar: Pulp
Effective Python Learning Memorandum Day 13 [13/100]
A memorandum about Python mock
Effective Python Learning Memorandum Day 3 [3/100]
Effective Python Learning Memorandum Day 5 [5/100]
Memorandum @ Python OR Seminar: Pandas
[python] Random number generation memorandum
Effective Python Learning Memorandum Day 4 [4/100]
Memorandum @ Python OR Seminar: scikit-learn
Effective Python Learning Memorandum Day 7 [7/100]
Effective Python Learning Memorandum Day 2 [2/100]
python parallel / asynchronous execution memorandum
ABC memorandum [ABC159 C --Maximum Volume] (Python)
Python pywin32 (win32com) Excel operation memorandum
[Python] A memorandum of beautiful soup4
python dict object memorandum (mysterious document)
ABC memorandum [ABC161 C --Replacing Integer] (Python)
Git & Github & python & VScode Personal memorandum
PIL (Python Imaging Library) installation memorandum
ABC memorandum [ABC158 C --Tax Increase] (Python)
Memorandum of beginners Python "isdigit" movement
Matplotlib memorandum
kafka python
linux memorandum
Python basics ⑤
python + lottery 6
Built-in python