Twice split in one expression?

Imagine that 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 it possible to simplify the performance of the same work in only one expression?

+5
source share
5 answers

You can get what you want, regardless of the platform, using os.path.basename to get the last part of the path, and then use os.path.splitext to get the file name without the extension.

from os.path import basename, splitext

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

os.path.basename os.path.splitext str.split re.split (, , , ), ( , ).

, " " , ( , , )

+20

, , ...

Florians , , ...

re.split() : '|', :

import re
inFile = "/adda/adas/sdas/hello.txt"
print re.split('\.|/', inFile)[-2]
+2
>>> inFile = "/adda/adas/sdas/hello.txt"
>>> inFile.split('/')[-1]
'hello.txt'
>>> inFile.split('/')[-1].split('.')[0]
'hello'
+1

, , os.path.split os.path.splitext

from os.path import split, splitext
path = "/adda/adas/sdas/hello.txt"
print splitext(split(path)[1])[0]

. https://docs.python.org/library/os.path.html

+1

, Regex-Ninja *, (, , : ...)

, ? , , , . , :

I assume that you want to separate the path, file name and file extension, if you separated "/", first you know that the file name should be in the last index of the array, then you can try to split only the last index to find out if you can find the file extension or not. Then you do not need to worry about whether there are dots in the path names.

* (Any reasonable users of regular expressions should not be offended.;)

0
source

All Articles