简体   繁体   中英

How do I extract only a part of a list 'member' in PYTHON?

My question is a bit basic, but as I'm a newbie in python (crossed over from GIS), please bear with me.

I have a python list which is based on the files the user inserts -

for example: inputlist =["c:\\\\files\\\\foobar.shp","c:\\\\files\\\\snafu.shp"]

how do I get the file names only (without the path or extesions) into a new list?

(desired output: ["foobar","snafu"] )

Thanks.

您可以为此使用python的列表推导:

new_list = [ splitext(basename(i))[0] for i in inputlist ]
[os.path.basename(p).rsplit(".", 1)[0] for p in inputlist]
import os.path
extLessBasename = lambda fn: os.path.splitext(os.path.basename(fn))[0]
fileNames = map(extLessBasename, inputlist)

This solution is also help you.

import os
inputlist =["/home/anupam/PycharmProjects/DataStructures/LogicalProgram/classvsstatic.py",
            "/home/anupam/PycharmProjects/DataStructures/LogicalProgram/decorators.py"]
filename_list = []
for i in inputlist:
    path_list =i.split('/')
    filename_with_extension = path_list[-1]
    filename_without_extension = os.path.splitext(filename_with_extension)[0]
    filename_list.append(filename_without_extension)

print(filename_list) 

According to windows file path. You can split with '//' small change in my code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM