[Tutor] Getting a directory listing with Python to MySQL
Steven D'Aprano
steve at pearwood.info
Wed Jul 23 03:31:48 CEST 2014
On Tue, Jul 22, 2014 at 04:10:02PM -0700, Eric Dannewitz wrote:
> Hello list, I'm new. I've done a few things in Python, but this one is posing problems.
>
> What I want to do is be able to parse a directory, say
> /Volumes/Stuff/Files/, and all the directories that might be in there,
> and be able to pick out file name, size, date modified, etc, and send
> that to a MySQL database. Any ideas? Sounds like it should be easy
> but......
os.listdir(path) returns all the entries under path (apart from '.' and
'..'). You can then test whether they are files, directories or links
with os.path.isdir, os.path.isfile, os.path.islink. (Remember that under
Linux and Unix, there things other than files and links that can live in
directories, e.g. named pipes.)
But rather than manually iterate through the contents of the directory,
os.walk already does that for you. Something like this ought to get you
started:
files = []
for dirpath, dirnames, filenames in os.walk(start_path):
pathnames = [os.path.join(dirpath, name) for name in filenames]
files.extend(pathnames)
That gets you a list of all the files under start_path. To check their
size, dates, etc. use the os.stat and os.lstat functions (os.stat
follows symbolic links, os.lstat does not). The stat module has a bunch
of symbolic constants which may be helpful for interpreting the results.
--
Steven
More information about the Tutor
mailing list