Get a list of files under a specific directory (absolute path format)
It was easy to do with the Pathlib module, which will be available from Python 3 series.
According to the following, pathlib is an object-oriented file path system.
https://docs.python.org/3.4/library/pathlib.html
From the result, I was able to get the list of files in a specific directory by using the following.
from pathlib import Path
from pathlib import PurePath
self.conf_dir = PurePath('/etc', 'apache', 'conf')
self.conf_files = list(self.conf_dir.glob('*'))
If you print each, the output will be as follows
self.conf_dir = PurePath('/etc', 'apache', 'conf')
print self.conf_dir
output
/etc/apache/conf
Get the obtained path entirely with glob . You can flexibly get the specified file by combining "" with a regular expression etc.
self.conf_files = list(self.conf_dir.glob('*'))
print(self.conf_files)
output
[PosixPath('/etc/apache/conf/http.test1.conf'),PosixPath('/etc/apache/conf/http.test2.conf')]
Recommended Posts