The comment section is real (although it is short) Thank you @takahirom!
ʻOs.listdir (path)will output a list of files and directories in
path`, but if you want to get only directories or only files, it will be a little bit. I thought about it.
The environment is Python 2.7.10 and the OS is Windows 7.
I think there is a smarter way to do it.
import glob
import os
def fileonly_listdir(path):
return [ i for i in os.listdir(path) if i not in [ j.replace(path, "").strip("\\") for j in glob.glob(os.path.join(path, "*") + "/")]]
Disassembled because it is difficult to understand.
import glob
import os
def fileonly_listdir(path):
list_dir = os.listdir(path) #Get a list of objects in a directory ... 1
dir_only_list = glob.glob(os.path.join(path, "*") + "/") #In a specific path, the end is"/"Object = directory only
#However,"path\\dir\\"Will be in the form
dir_only_list = [ i.replace(path, "").strip("\\") for i in dir_only_list ] #Eliminate the obstacles ... 2
file_only_list = [ i for i in list_dir if i not in dir_only_list ] #Subtract 1 to 2
return file_only_list
So if you want a list of directories only
import glob
[ i.replace(path, "").strip("\\") for i in glob.glob(os.path.join(path, "*") + "/")]
Is fine.
Nested list comprehensions are very difficult to understand, so it may be better to use filter
.
Recommended Posts