Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

python - How to remove a file from Path object in Pathlib module?

I have a Path Object representing C:UsersusersDownloadsimg.jpg. How do I get it so the Path only represents C:UsersuserDownloads? I don't want to delete the file, but rather go back in the Path object itself.

from pathlib import Path
path = Path('C:/Users/user/Downloads/img.jpg')
# Want to get path only to C:UsersuserDownloads
question from:https://stackoverflow.com/questions/65837297/how-to-remove-a-file-from-path-object-in-pathlib-module

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I would utilize the PurePath class within pathlib as follows:

from pathlib import PurePath
path = PurePath('C:/Users/user/Downloads/img.jpg')
parent = path.parents[0]

This yields: PureWindowsPath('C:/Users/users/Downloads')


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...