split twice in the same expression?

Imagine I have the following:

inFile = "/adda/adas/sdas/hello.txt"

# that instruction give me hello.txt
Name = inFile.name.split("/") [-1]

# that one give me the name I want - just hello
Name1 = Name.split(".") [0]

Is there any chance to simplify that doing the same job in just one expression?

Answers


You can get what you want platform independently by using os.path.basename to get the last part of a path and then use os.path.splitext to get the filename without extension.

from os.path import basename, splitext

pathname = "/adda/adas/sdas/hello.txt"
name, extension = splitext(basename(pathname))
print name # --> "hello"

Using os.path.basename and os.path.splitext instead of str.split, or re.split is more proper (and therefore received more points then any other answer) because it does not break down on other platforms that use different path separators (you would be surprised how varried this can be).

It also carries most points because it answers your question for "one line" precisely and is aesthetically more pleasing then your example (even though that is debatable as are all questions of taste)


Need Your Help

Make big quotes with <blockquote>

html block quote

Some years ago, I used the tag to create a quote on my site (with big quotation marks).

Set System propery to Null in Java

java system-properties

In my unit tests I need to set the "workingDir" system property to Null.