Use to list all files and directories. And then filter it in a List Comprehensions.Path.glob()
p = Path(r'C:\Users\akrio\Desktop\Test').glob('**/*')
files = [x for x in p if x.is_file()]
pathlib module: returns everything inside a directory -- including both files and directories.os.listdir()
's os.path can be used to only list files:isfile()
from os import listdir
from os.path import isfile, join
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
Alternatively, yields two lists for each directory it visits -- one for files and one for dirs. If you only want the top directory you can break the first time it yields:os.walk()
from os import walk
f = []
for (dirpath, dirnames, filenames) in walk(mypath):
f.extend(filenames)
break
or, shorter:
from os import walk
filenames = next(walk(mypath), (None, None, []))[2] # [] if no file
It looks like there is a element that contains all the parent directories of a given path. E.g., if you start with:parents
>>> import pathlib
>>> p = pathlib.Path('/path/to/my/file')
Then is the directory containing p.parents[0]:file
>>> p.parents[0]
PosixPath('/path/to/my')
...and will be the next directory up:p.parents[1]
>>> p.parents[1]
PosixPath('/path/to')
Etc.
is another way to ask for p.parent. You can convert a p.parents[0] into a string and get pretty much what you would expect:Path
>>> str(p.parent)
'/path/to/my'
And also on any you can use the Path method to get an absolute path:.absolute()
>>> os.chdir('/etc')
>>> p = pathlib.Path('../relative/path')
>>> str(p.parent)
'../relative'
>>> str(p.parent.absolute())
'/etc/../relative'
Note that and os.path.dirname treat paths with a trailing slash differently. The pathlib parent of pathlib is some/path/:some
>>> p = pathlib.Path('some/path/')
>>> p.parent
PosixPath('some')
While on os.path.dirname returns some/path/:some/path
>>> os.path.dirname('some/path/')
'some/path'
import glob
jpgFilenamesList = glob.glob('145592*.jpg')
See in python documenttionglob
This is a simple generator expression:
files = (file for file in os.listdir(path)
if os.path.isfile(os.path.join(path, file)))
for file in files: # You could shorten this to one line, but it runs on a bit.
...
Or you could make a generator function if it suited you better:
def files(path):
for file in os.listdir(path):
if os.path.isfile(os.path.join(path, file)):
yield file
Then simply:
for file in files(path):
...
It seems that this method was brought up in a bug report here. Some code was written (given here) but unfortunately it doesn't seem that it made it into the final Python 3.4 release.
Incidentally the code that was proposed was extremely similar to the code you have in your question:
# As a method of a Path object
def expanduser(self):
""" Return a new path with expanded ~ and ~user constructs
(as returned by os.path.expanduser)
"""
return self.__class__(os.path.expanduser(str(self)))
Here is a rudimentary subclassed version which subclasses PathTest (I'm on a Windows box but you could replace it with WindowsPath). It adds a PosixPath based on the code that was submitted in the bug report.classmethod
from pathlib import WindowsPath
import os.path
class PathTest(WindowsPath):
def __new__(cls, *args, **kwargs):
return super(PathTest, cls).__new__(cls, *args, **kwargs)
@classmethod
def expanduser(cls):
""" Return a new path with expanded ~ and ~user constructs
(as returned by os.path.expanduser)
"""
return cls(os.path.expanduser('~'))
p = PathTest('C:/')
print(p) # 'C:/'
q = PathTest.expanduser()
print(q) # C:\Users\Username