Extracting the parent, leaf, and extension from a valid pathFile validation and unit testingExtracting lines from a bytearrayExtracting a Decimal from a stringExtracting the last component (basename) of a filesystem pathExtracting data from a stringParsing string and extracting meaningful informationExtracting the src attribute and content of <script> tags in HTML files in a directoryCleaning and extracting meaningful text from tweetsExtracting specific words from PANDAS dataframeExtracting address information from non-formatted text
What's the role of the Receiver/Transmitter in Avengers Endgame?
shebang or not shebang
I want to write a blog post building upon someone else's paper, how can I properly cite/credit them?
All of my Firefox add-ons have been disabled suddenly, how can I re-enable them?
What is the meaning of "matter" in physics?
Do the Zhentarim fire members for killing fellow members?
Can you just subtract the challenge rating of friendly NPCs?
GitLab account hacked and repo wiped
Why did Dr. Strange keep looking into the future after the snap?
why it is 2>&1 and not 2>>&1 to append to a log file
What's weird about Proto-Indo-European Stops?
What is more safe for browsing the web: PC or smartphone?
Convert Numbers To Emoji Math
Concatenate all values of the same XML element using XPath/XQuery
If quadruped mammals evolve to become bipedal will their breast or nipple change position?
HTML folder located within IOS Image file?
Select list elements based on other list
Why doesn't increasing the temperature of something like wood or paper set them on fire?
Clauses with 3 infinitives at the end
What's the 2-minute timer on mobile Deutsche Bahn tickets?
Test whether a string is in a list with variable
How to increase row height of a table and vertically "align middle"?
Can a player choose to add detail and flavor to their character's spells and abilities?
How do I give a darkroom course without negs from the attendees?
Extracting the parent, leaf, and extension from a valid path
File validation and unit testingExtracting lines from a bytearrayExtracting a Decimal from a stringExtracting the last component (basename) of a filesystem pathExtracting data from a stringParsing string and extracting meaningful informationExtracting the src attribute and content of <script> tags in HTML files in a directoryCleaning and extracting meaningful text from tweetsExtracting specific words from PANDAS dataframeExtracting address information from non-formatted text
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
$begingroup$
Powershell has the Split-Path
cmdlet which allows you to extract the Parent and Leaf of a file. In PS version 6, you can extract the extension, with the -Extension
switch. Why this wasn't a feature of PS version 4 and greater I don't know, so I decided to write my own version in Python.
PathUtilities:
# PathUtilities.py
def parse_file_path(file_path : str):
"""
The function a user must call if they want to parse a file path.
It accepts, validates, and returns a tuple containing
the elements (parent, leaf, and extension)
of the path.
The path doesn't haven't exist.
Args:
file_path : str - A string representing a file path.
Returns:
A tuple containing all the parsed elements.
"""
_determine_if_the_drive_letter_is_valid(file_path=file_path)
_determine_if_second_element_is_valid(file_path=file_path)
_determine_if_the_string_contains_forbidden_characters(string_to_validate = file_path[2:])
return _construct_path_tuple(file_path=file_path)
def _determine_if_the_drive_letter_is_valid(file_path : str):
"""
Determines if the drive letter is a letter.
Raises a TypeError if the first letter is invalid.
Args:
file_path - see parse_file_path function.
Returns:
None
"""
drive_letter = file_path[:1]
if not drive_letter.isalpha():
raise TypeError("Drive Letter is invalid.")
def _determine_if_second_element_is_valid(file_path : str):
"""
Determine if the second element in the path is a :
Raises a ValueError if the second element is invalid.
Args:
file_path - see parse_file_path function.
Returns:
None
"""
valid_element = ":"
second_element = file_path[1]
if second_element != valid_element:
raise ValueError("Invalid characters in path.")
def _determine_if_the_string_contains_forbidden_characters(*additional_characters, string_to_validate : str):
"""
Determine if the string contains forbidden elements.
Raises a ValueError if any forbidden character is found.
Args:
string_to_validate : str - The string we're going to test.
*additional_characters - To make the function reusable we accept additional elements to be tested
in addition to the list of forbidden characters.
"""
# Contains all the forbidden characters in Windows paths.
# Note the 4 slashes, because paths use \ to seperate folders and drives, we have to validate
# if the user entered additional slashes, two slashes is fine, but more are forbidden.
# Example: C:\Users\Sveta\\emp_list.txt - invalid.
forbidden_characters = ["<", ">", ":", "/", '"', "|", "?", "*"," ", "\\"]
for forbidden_character in forbidden_characters:
if forbidden_character in string_to_validate:
raise ValueError("Invalid characters in path.")
if additional_characters:
for character in additional_characters:
if character in string_to_validate:
raise ValueError("Invalid characters in path.")
def _parse_extension(string_to_parse : str):
"""
Split the file path on the period, validate, and return the extension with the period.
Raises a ValueError if the extension contains forbidden characters.
Args:
file_path - see parse_file_path function
Returns:
the extension of the file or None, if no file extension is present.
"""
# file and folder names are allowed to have periods, so we split on that,
# but we're only interested in the last element, the extension.
split_extension = string_to_parse.split(".")[-1]
# if the string doesn't have a file extension, we return None.
if len(split_extension) == len(string_to_parse):
return None
def _determine_if_the_string_contains_forbidden_characters("\", string_to_validate = split_extension)
return ".0".format(split_extension)
def _parse_leaf(file_path : str):
"""
Split the file path using \ and returns the last element.
Args:
file_path - see parse_file_path function.
Returns:
the last element of the file path, in this case the filename with extension.
"""
delimiter = "\"
return file_path.split(delimiter)[-1]
def _parse_parent(file_path : str, leaf: str):
"""
Take the leaf, and use it as a delimiter to extract the parent directory, without the trailing slash.
Args:
file_path - see parse_file_path function.
leaf : str - the leaf of our file path.
Returns:
The first element in our list, our parent directory.
"""
delimiter = "\0".format(leaf)
return file_path.split(delimiter)[0]
def _construct_path_tuple(file_path : str):
"""
Constructs a tuple representing the elements of the file path.
Args:
file_path - see parse_file_path function.
Returns:
A tuple that contains the file elements.
"""
leaf = _parse_leaf(file_path = file_path)
extension = _parse_extension(string_to_parse = leaf)
parent = _parse_parent(file_path = file_path, leaf=leaf)
return (parent, leaf, extension)
Main:
import pathutilities
def main():
try:
path = pathutilities.parse_file_path("C:\Users\Sveta\Employee\emp_list.txt")
except (TypeError, ValueError) as error:
print(error)
else:
parent, leaf, extension = path
print(parent, leaf, extension)
# Output:
# C:UsersSvetaEmployee emp_list.txt .txt
if __name__ == '__main__':
main()
If it makes it easier to read, here is my Github link.
python python-3.x strings parsing
New contributor
$endgroup$
add a comment |
$begingroup$
Powershell has the Split-Path
cmdlet which allows you to extract the Parent and Leaf of a file. In PS version 6, you can extract the extension, with the -Extension
switch. Why this wasn't a feature of PS version 4 and greater I don't know, so I decided to write my own version in Python.
PathUtilities:
# PathUtilities.py
def parse_file_path(file_path : str):
"""
The function a user must call if they want to parse a file path.
It accepts, validates, and returns a tuple containing
the elements (parent, leaf, and extension)
of the path.
The path doesn't haven't exist.
Args:
file_path : str - A string representing a file path.
Returns:
A tuple containing all the parsed elements.
"""
_determine_if_the_drive_letter_is_valid(file_path=file_path)
_determine_if_second_element_is_valid(file_path=file_path)
_determine_if_the_string_contains_forbidden_characters(string_to_validate = file_path[2:])
return _construct_path_tuple(file_path=file_path)
def _determine_if_the_drive_letter_is_valid(file_path : str):
"""
Determines if the drive letter is a letter.
Raises a TypeError if the first letter is invalid.
Args:
file_path - see parse_file_path function.
Returns:
None
"""
drive_letter = file_path[:1]
if not drive_letter.isalpha():
raise TypeError("Drive Letter is invalid.")
def _determine_if_second_element_is_valid(file_path : str):
"""
Determine if the second element in the path is a :
Raises a ValueError if the second element is invalid.
Args:
file_path - see parse_file_path function.
Returns:
None
"""
valid_element = ":"
second_element = file_path[1]
if second_element != valid_element:
raise ValueError("Invalid characters in path.")
def _determine_if_the_string_contains_forbidden_characters(*additional_characters, string_to_validate : str):
"""
Determine if the string contains forbidden elements.
Raises a ValueError if any forbidden character is found.
Args:
string_to_validate : str - The string we're going to test.
*additional_characters - To make the function reusable we accept additional elements to be tested
in addition to the list of forbidden characters.
"""
# Contains all the forbidden characters in Windows paths.
# Note the 4 slashes, because paths use \ to seperate folders and drives, we have to validate
# if the user entered additional slashes, two slashes is fine, but more are forbidden.
# Example: C:\Users\Sveta\\emp_list.txt - invalid.
forbidden_characters = ["<", ">", ":", "/", '"', "|", "?", "*"," ", "\\"]
for forbidden_character in forbidden_characters:
if forbidden_character in string_to_validate:
raise ValueError("Invalid characters in path.")
if additional_characters:
for character in additional_characters:
if character in string_to_validate:
raise ValueError("Invalid characters in path.")
def _parse_extension(string_to_parse : str):
"""
Split the file path on the period, validate, and return the extension with the period.
Raises a ValueError if the extension contains forbidden characters.
Args:
file_path - see parse_file_path function
Returns:
the extension of the file or None, if no file extension is present.
"""
# file and folder names are allowed to have periods, so we split on that,
# but we're only interested in the last element, the extension.
split_extension = string_to_parse.split(".")[-1]
# if the string doesn't have a file extension, we return None.
if len(split_extension) == len(string_to_parse):
return None
def _determine_if_the_string_contains_forbidden_characters("\", string_to_validate = split_extension)
return ".0".format(split_extension)
def _parse_leaf(file_path : str):
"""
Split the file path using \ and returns the last element.
Args:
file_path - see parse_file_path function.
Returns:
the last element of the file path, in this case the filename with extension.
"""
delimiter = "\"
return file_path.split(delimiter)[-1]
def _parse_parent(file_path : str, leaf: str):
"""
Take the leaf, and use it as a delimiter to extract the parent directory, without the trailing slash.
Args:
file_path - see parse_file_path function.
leaf : str - the leaf of our file path.
Returns:
The first element in our list, our parent directory.
"""
delimiter = "\0".format(leaf)
return file_path.split(delimiter)[0]
def _construct_path_tuple(file_path : str):
"""
Constructs a tuple representing the elements of the file path.
Args:
file_path - see parse_file_path function.
Returns:
A tuple that contains the file elements.
"""
leaf = _parse_leaf(file_path = file_path)
extension = _parse_extension(string_to_parse = leaf)
parent = _parse_parent(file_path = file_path, leaf=leaf)
return (parent, leaf, extension)
Main:
import pathutilities
def main():
try:
path = pathutilities.parse_file_path("C:\Users\Sveta\Employee\emp_list.txt")
except (TypeError, ValueError) as error:
print(error)
else:
parent, leaf, extension = path
print(parent, leaf, extension)
# Output:
# C:UsersSvetaEmployee emp_list.txt .txt
if __name__ == '__main__':
main()
If it makes it easier to read, here is my Github link.
python python-3.x strings parsing
New contributor
$endgroup$
1
$begingroup$
Are you aware of theos.path
module?
$endgroup$
– 200_success
6 hours ago
2
$begingroup$
@200_success Since this is Python 3, usingpathlib
can result in a cleaner interface.
$endgroup$
– Peilonrayz
5 hours ago
add a comment |
$begingroup$
Powershell has the Split-Path
cmdlet which allows you to extract the Parent and Leaf of a file. In PS version 6, you can extract the extension, with the -Extension
switch. Why this wasn't a feature of PS version 4 and greater I don't know, so I decided to write my own version in Python.
PathUtilities:
# PathUtilities.py
def parse_file_path(file_path : str):
"""
The function a user must call if they want to parse a file path.
It accepts, validates, and returns a tuple containing
the elements (parent, leaf, and extension)
of the path.
The path doesn't haven't exist.
Args:
file_path : str - A string representing a file path.
Returns:
A tuple containing all the parsed elements.
"""
_determine_if_the_drive_letter_is_valid(file_path=file_path)
_determine_if_second_element_is_valid(file_path=file_path)
_determine_if_the_string_contains_forbidden_characters(string_to_validate = file_path[2:])
return _construct_path_tuple(file_path=file_path)
def _determine_if_the_drive_letter_is_valid(file_path : str):
"""
Determines if the drive letter is a letter.
Raises a TypeError if the first letter is invalid.
Args:
file_path - see parse_file_path function.
Returns:
None
"""
drive_letter = file_path[:1]
if not drive_letter.isalpha():
raise TypeError("Drive Letter is invalid.")
def _determine_if_second_element_is_valid(file_path : str):
"""
Determine if the second element in the path is a :
Raises a ValueError if the second element is invalid.
Args:
file_path - see parse_file_path function.
Returns:
None
"""
valid_element = ":"
second_element = file_path[1]
if second_element != valid_element:
raise ValueError("Invalid characters in path.")
def _determine_if_the_string_contains_forbidden_characters(*additional_characters, string_to_validate : str):
"""
Determine if the string contains forbidden elements.
Raises a ValueError if any forbidden character is found.
Args:
string_to_validate : str - The string we're going to test.
*additional_characters - To make the function reusable we accept additional elements to be tested
in addition to the list of forbidden characters.
"""
# Contains all the forbidden characters in Windows paths.
# Note the 4 slashes, because paths use \ to seperate folders and drives, we have to validate
# if the user entered additional slashes, two slashes is fine, but more are forbidden.
# Example: C:\Users\Sveta\\emp_list.txt - invalid.
forbidden_characters = ["<", ">", ":", "/", '"', "|", "?", "*"," ", "\\"]
for forbidden_character in forbidden_characters:
if forbidden_character in string_to_validate:
raise ValueError("Invalid characters in path.")
if additional_characters:
for character in additional_characters:
if character in string_to_validate:
raise ValueError("Invalid characters in path.")
def _parse_extension(string_to_parse : str):
"""
Split the file path on the period, validate, and return the extension with the period.
Raises a ValueError if the extension contains forbidden characters.
Args:
file_path - see parse_file_path function
Returns:
the extension of the file or None, if no file extension is present.
"""
# file and folder names are allowed to have periods, so we split on that,
# but we're only interested in the last element, the extension.
split_extension = string_to_parse.split(".")[-1]
# if the string doesn't have a file extension, we return None.
if len(split_extension) == len(string_to_parse):
return None
def _determine_if_the_string_contains_forbidden_characters("\", string_to_validate = split_extension)
return ".0".format(split_extension)
def _parse_leaf(file_path : str):
"""
Split the file path using \ and returns the last element.
Args:
file_path - see parse_file_path function.
Returns:
the last element of the file path, in this case the filename with extension.
"""
delimiter = "\"
return file_path.split(delimiter)[-1]
def _parse_parent(file_path : str, leaf: str):
"""
Take the leaf, and use it as a delimiter to extract the parent directory, without the trailing slash.
Args:
file_path - see parse_file_path function.
leaf : str - the leaf of our file path.
Returns:
The first element in our list, our parent directory.
"""
delimiter = "\0".format(leaf)
return file_path.split(delimiter)[0]
def _construct_path_tuple(file_path : str):
"""
Constructs a tuple representing the elements of the file path.
Args:
file_path - see parse_file_path function.
Returns:
A tuple that contains the file elements.
"""
leaf = _parse_leaf(file_path = file_path)
extension = _parse_extension(string_to_parse = leaf)
parent = _parse_parent(file_path = file_path, leaf=leaf)
return (parent, leaf, extension)
Main:
import pathutilities
def main():
try:
path = pathutilities.parse_file_path("C:\Users\Sveta\Employee\emp_list.txt")
except (TypeError, ValueError) as error:
print(error)
else:
parent, leaf, extension = path
print(parent, leaf, extension)
# Output:
# C:UsersSvetaEmployee emp_list.txt .txt
if __name__ == '__main__':
main()
If it makes it easier to read, here is my Github link.
python python-3.x strings parsing
New contributor
$endgroup$
Powershell has the Split-Path
cmdlet which allows you to extract the Parent and Leaf of a file. In PS version 6, you can extract the extension, with the -Extension
switch. Why this wasn't a feature of PS version 4 and greater I don't know, so I decided to write my own version in Python.
PathUtilities:
# PathUtilities.py
def parse_file_path(file_path : str):
"""
The function a user must call if they want to parse a file path.
It accepts, validates, and returns a tuple containing
the elements (parent, leaf, and extension)
of the path.
The path doesn't haven't exist.
Args:
file_path : str - A string representing a file path.
Returns:
A tuple containing all the parsed elements.
"""
_determine_if_the_drive_letter_is_valid(file_path=file_path)
_determine_if_second_element_is_valid(file_path=file_path)
_determine_if_the_string_contains_forbidden_characters(string_to_validate = file_path[2:])
return _construct_path_tuple(file_path=file_path)
def _determine_if_the_drive_letter_is_valid(file_path : str):
"""
Determines if the drive letter is a letter.
Raises a TypeError if the first letter is invalid.
Args:
file_path - see parse_file_path function.
Returns:
None
"""
drive_letter = file_path[:1]
if not drive_letter.isalpha():
raise TypeError("Drive Letter is invalid.")
def _determine_if_second_element_is_valid(file_path : str):
"""
Determine if the second element in the path is a :
Raises a ValueError if the second element is invalid.
Args:
file_path - see parse_file_path function.
Returns:
None
"""
valid_element = ":"
second_element = file_path[1]
if second_element != valid_element:
raise ValueError("Invalid characters in path.")
def _determine_if_the_string_contains_forbidden_characters(*additional_characters, string_to_validate : str):
"""
Determine if the string contains forbidden elements.
Raises a ValueError if any forbidden character is found.
Args:
string_to_validate : str - The string we're going to test.
*additional_characters - To make the function reusable we accept additional elements to be tested
in addition to the list of forbidden characters.
"""
# Contains all the forbidden characters in Windows paths.
# Note the 4 slashes, because paths use \ to seperate folders and drives, we have to validate
# if the user entered additional slashes, two slashes is fine, but more are forbidden.
# Example: C:\Users\Sveta\\emp_list.txt - invalid.
forbidden_characters = ["<", ">", ":", "/", '"', "|", "?", "*"," ", "\\"]
for forbidden_character in forbidden_characters:
if forbidden_character in string_to_validate:
raise ValueError("Invalid characters in path.")
if additional_characters:
for character in additional_characters:
if character in string_to_validate:
raise ValueError("Invalid characters in path.")
def _parse_extension(string_to_parse : str):
"""
Split the file path on the period, validate, and return the extension with the period.
Raises a ValueError if the extension contains forbidden characters.
Args:
file_path - see parse_file_path function
Returns:
the extension of the file or None, if no file extension is present.
"""
# file and folder names are allowed to have periods, so we split on that,
# but we're only interested in the last element, the extension.
split_extension = string_to_parse.split(".")[-1]
# if the string doesn't have a file extension, we return None.
if len(split_extension) == len(string_to_parse):
return None
def _determine_if_the_string_contains_forbidden_characters("\", string_to_validate = split_extension)
return ".0".format(split_extension)
def _parse_leaf(file_path : str):
"""
Split the file path using \ and returns the last element.
Args:
file_path - see parse_file_path function.
Returns:
the last element of the file path, in this case the filename with extension.
"""
delimiter = "\"
return file_path.split(delimiter)[-1]
def _parse_parent(file_path : str, leaf: str):
"""
Take the leaf, and use it as a delimiter to extract the parent directory, without the trailing slash.
Args:
file_path - see parse_file_path function.
leaf : str - the leaf of our file path.
Returns:
The first element in our list, our parent directory.
"""
delimiter = "\0".format(leaf)
return file_path.split(delimiter)[0]
def _construct_path_tuple(file_path : str):
"""
Constructs a tuple representing the elements of the file path.
Args:
file_path - see parse_file_path function.
Returns:
A tuple that contains the file elements.
"""
leaf = _parse_leaf(file_path = file_path)
extension = _parse_extension(string_to_parse = leaf)
parent = _parse_parent(file_path = file_path, leaf=leaf)
return (parent, leaf, extension)
Main:
import pathutilities
def main():
try:
path = pathutilities.parse_file_path("C:\Users\Sveta\Employee\emp_list.txt")
except (TypeError, ValueError) as error:
print(error)
else:
parent, leaf, extension = path
print(parent, leaf, extension)
# Output:
# C:UsersSvetaEmployee emp_list.txt .txt
if __name__ == '__main__':
main()
If it makes it easier to read, here is my Github link.
python python-3.x strings parsing
python python-3.x strings parsing
New contributor
New contributor
edited 6 hours ago
200_success
132k20159424
132k20159424
New contributor
asked 7 hours ago
nsonlinensonline
1212
1212
New contributor
New contributor
1
$begingroup$
Are you aware of theos.path
module?
$endgroup$
– 200_success
6 hours ago
2
$begingroup$
@200_success Since this is Python 3, usingpathlib
can result in a cleaner interface.
$endgroup$
– Peilonrayz
5 hours ago
add a comment |
1
$begingroup$
Are you aware of theos.path
module?
$endgroup$
– 200_success
6 hours ago
2
$begingroup$
@200_success Since this is Python 3, usingpathlib
can result in a cleaner interface.
$endgroup$
– Peilonrayz
5 hours ago
1
1
$begingroup$
Are you aware of the
os.path
module?$endgroup$
– 200_success
6 hours ago
$begingroup$
Are you aware of the
os.path
module?$endgroup$
– 200_success
6 hours ago
2
2
$begingroup$
@200_success Since this is Python 3, using
pathlib
can result in a cleaner interface.$endgroup$
– Peilonrayz
5 hours ago
$begingroup$
@200_success Since this is Python 3, using
pathlib
can result in a cleaner interface.$endgroup$
– Peilonrayz
5 hours ago
add a comment |
1 Answer
1
active
oldest
votes
$begingroup$
PurePath.drive
allows UNC drives, but yours doesn't.pathlib
implements everything you need. Which is available from Python 3.4.
Note: This code doesn't require the drive to be set. That can be achieved by checking PurePath.drive
if it is needed.
from pathlib import PurePath
def parse_file_path(path):
path = PurePath(path)
return str(path.parent), path.name, path.suffix or None
If you're not running 3.4+ then the equivalent in os.path
, is pretty simple too. But IMO is pretty unsightly.
You can also check the drive through os.path.splitdrive
.
import os.path
def parse_file_path(path):
name = os.path.basename(path)
return (
os.path.dirname(path),
name,
os.path.splitext(name)[1] or None
)
$endgroup$
1
$begingroup$
@Graipher Thanks, you seem to catch all my errors atm :) Fixed and I have double-checked the other function calls are the correct values.
$endgroup$
– Peilonrayz
1 hour ago
$begingroup$
Only when I stumble upon them in the HNQs. But a lot of your recent answers seem to make it there :)
$endgroup$
– Graipher
1 hour ago
$begingroup$
Seems that way. It's really helping me bridge the gap to between us in Python-3.x, ;P
$endgroup$
– Peilonrayz
1 hour ago
$begingroup$
So far so good for a better alternative. But it's not much of a code review. And OP could definitely benefit from a code review.
$endgroup$
– Konrad Rudolph
1 hour ago
$begingroup$
@KonradRudolph What do you feel is lacking in my answer? I may be able to provide it if I know what 'it' is.
$endgroup$
– Peilonrayz
1 hour ago
|
show 1 more comment
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "196"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
nsonline is a new contributor. Be nice, and check out our Code of Conduct.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f219817%2fextracting-the-parent-leaf-and-extension-from-a-valid-path%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
$begingroup$
PurePath.drive
allows UNC drives, but yours doesn't.pathlib
implements everything you need. Which is available from Python 3.4.
Note: This code doesn't require the drive to be set. That can be achieved by checking PurePath.drive
if it is needed.
from pathlib import PurePath
def parse_file_path(path):
path = PurePath(path)
return str(path.parent), path.name, path.suffix or None
If you're not running 3.4+ then the equivalent in os.path
, is pretty simple too. But IMO is pretty unsightly.
You can also check the drive through os.path.splitdrive
.
import os.path
def parse_file_path(path):
name = os.path.basename(path)
return (
os.path.dirname(path),
name,
os.path.splitext(name)[1] or None
)
$endgroup$
1
$begingroup$
@Graipher Thanks, you seem to catch all my errors atm :) Fixed and I have double-checked the other function calls are the correct values.
$endgroup$
– Peilonrayz
1 hour ago
$begingroup$
Only when I stumble upon them in the HNQs. But a lot of your recent answers seem to make it there :)
$endgroup$
– Graipher
1 hour ago
$begingroup$
Seems that way. It's really helping me bridge the gap to between us in Python-3.x, ;P
$endgroup$
– Peilonrayz
1 hour ago
$begingroup$
So far so good for a better alternative. But it's not much of a code review. And OP could definitely benefit from a code review.
$endgroup$
– Konrad Rudolph
1 hour ago
$begingroup$
@KonradRudolph What do you feel is lacking in my answer? I may be able to provide it if I know what 'it' is.
$endgroup$
– Peilonrayz
1 hour ago
|
show 1 more comment
$begingroup$
PurePath.drive
allows UNC drives, but yours doesn't.pathlib
implements everything you need. Which is available from Python 3.4.
Note: This code doesn't require the drive to be set. That can be achieved by checking PurePath.drive
if it is needed.
from pathlib import PurePath
def parse_file_path(path):
path = PurePath(path)
return str(path.parent), path.name, path.suffix or None
If you're not running 3.4+ then the equivalent in os.path
, is pretty simple too. But IMO is pretty unsightly.
You can also check the drive through os.path.splitdrive
.
import os.path
def parse_file_path(path):
name = os.path.basename(path)
return (
os.path.dirname(path),
name,
os.path.splitext(name)[1] or None
)
$endgroup$
1
$begingroup$
@Graipher Thanks, you seem to catch all my errors atm :) Fixed and I have double-checked the other function calls are the correct values.
$endgroup$
– Peilonrayz
1 hour ago
$begingroup$
Only when I stumble upon them in the HNQs. But a lot of your recent answers seem to make it there :)
$endgroup$
– Graipher
1 hour ago
$begingroup$
Seems that way. It's really helping me bridge the gap to between us in Python-3.x, ;P
$endgroup$
– Peilonrayz
1 hour ago
$begingroup$
So far so good for a better alternative. But it's not much of a code review. And OP could definitely benefit from a code review.
$endgroup$
– Konrad Rudolph
1 hour ago
$begingroup$
@KonradRudolph What do you feel is lacking in my answer? I may be able to provide it if I know what 'it' is.
$endgroup$
– Peilonrayz
1 hour ago
|
show 1 more comment
$begingroup$
PurePath.drive
allows UNC drives, but yours doesn't.pathlib
implements everything you need. Which is available from Python 3.4.
Note: This code doesn't require the drive to be set. That can be achieved by checking PurePath.drive
if it is needed.
from pathlib import PurePath
def parse_file_path(path):
path = PurePath(path)
return str(path.parent), path.name, path.suffix or None
If you're not running 3.4+ then the equivalent in os.path
, is pretty simple too. But IMO is pretty unsightly.
You can also check the drive through os.path.splitdrive
.
import os.path
def parse_file_path(path):
name = os.path.basename(path)
return (
os.path.dirname(path),
name,
os.path.splitext(name)[1] or None
)
$endgroup$
PurePath.drive
allows UNC drives, but yours doesn't.pathlib
implements everything you need. Which is available from Python 3.4.
Note: This code doesn't require the drive to be set. That can be achieved by checking PurePath.drive
if it is needed.
from pathlib import PurePath
def parse_file_path(path):
path = PurePath(path)
return str(path.parent), path.name, path.suffix or None
If you're not running 3.4+ then the equivalent in os.path
, is pretty simple too. But IMO is pretty unsightly.
You can also check the drive through os.path.splitdrive
.
import os.path
def parse_file_path(path):
name = os.path.basename(path)
return (
os.path.dirname(path),
name,
os.path.splitext(name)[1] or None
)
edited 1 hour ago
answered 6 hours ago
PeilonrayzPeilonrayz
27.2k341113
27.2k341113
1
$begingroup$
@Graipher Thanks, you seem to catch all my errors atm :) Fixed and I have double-checked the other function calls are the correct values.
$endgroup$
– Peilonrayz
1 hour ago
$begingroup$
Only when I stumble upon them in the HNQs. But a lot of your recent answers seem to make it there :)
$endgroup$
– Graipher
1 hour ago
$begingroup$
Seems that way. It's really helping me bridge the gap to between us in Python-3.x, ;P
$endgroup$
– Peilonrayz
1 hour ago
$begingroup$
So far so good for a better alternative. But it's not much of a code review. And OP could definitely benefit from a code review.
$endgroup$
– Konrad Rudolph
1 hour ago
$begingroup$
@KonradRudolph What do you feel is lacking in my answer? I may be able to provide it if I know what 'it' is.
$endgroup$
– Peilonrayz
1 hour ago
|
show 1 more comment
1
$begingroup$
@Graipher Thanks, you seem to catch all my errors atm :) Fixed and I have double-checked the other function calls are the correct values.
$endgroup$
– Peilonrayz
1 hour ago
$begingroup$
Only when I stumble upon them in the HNQs. But a lot of your recent answers seem to make it there :)
$endgroup$
– Graipher
1 hour ago
$begingroup$
Seems that way. It's really helping me bridge the gap to between us in Python-3.x, ;P
$endgroup$
– Peilonrayz
1 hour ago
$begingroup$
So far so good for a better alternative. But it's not much of a code review. And OP could definitely benefit from a code review.
$endgroup$
– Konrad Rudolph
1 hour ago
$begingroup$
@KonradRudolph What do you feel is lacking in my answer? I may be able to provide it if I know what 'it' is.
$endgroup$
– Peilonrayz
1 hour ago
1
1
$begingroup$
@Graipher Thanks, you seem to catch all my errors atm :) Fixed and I have double-checked the other function calls are the correct values.
$endgroup$
– Peilonrayz
1 hour ago
$begingroup$
@Graipher Thanks, you seem to catch all my errors atm :) Fixed and I have double-checked the other function calls are the correct values.
$endgroup$
– Peilonrayz
1 hour ago
$begingroup$
Only when I stumble upon them in the HNQs. But a lot of your recent answers seem to make it there :)
$endgroup$
– Graipher
1 hour ago
$begingroup$
Only when I stumble upon them in the HNQs. But a lot of your recent answers seem to make it there :)
$endgroup$
– Graipher
1 hour ago
$begingroup$
Seems that way. It's really helping me bridge the gap to between us in Python-3.x, ;P
$endgroup$
– Peilonrayz
1 hour ago
$begingroup$
Seems that way. It's really helping me bridge the gap to between us in Python-3.x, ;P
$endgroup$
– Peilonrayz
1 hour ago
$begingroup$
So far so good for a better alternative. But it's not much of a code review. And OP could definitely benefit from a code review.
$endgroup$
– Konrad Rudolph
1 hour ago
$begingroup$
So far so good for a better alternative. But it's not much of a code review. And OP could definitely benefit from a code review.
$endgroup$
– Konrad Rudolph
1 hour ago
$begingroup$
@KonradRudolph What do you feel is lacking in my answer? I may be able to provide it if I know what 'it' is.
$endgroup$
– Peilonrayz
1 hour ago
$begingroup$
@KonradRudolph What do you feel is lacking in my answer? I may be able to provide it if I know what 'it' is.
$endgroup$
– Peilonrayz
1 hour ago
|
show 1 more comment
nsonline is a new contributor. Be nice, and check out our Code of Conduct.
nsonline is a new contributor. Be nice, and check out our Code of Conduct.
nsonline is a new contributor. Be nice, and check out our Code of Conduct.
nsonline is a new contributor. Be nice, and check out our Code of Conduct.
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f219817%2fextracting-the-parent-leaf-and-extension-from-a-valid-path%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
$begingroup$
Are you aware of the
os.path
module?$endgroup$
– 200_success
6 hours ago
2
$begingroup$
@200_success Since this is Python 3, using
pathlib
can result in a cleaner interface.$endgroup$
– Peilonrayz
5 hours ago