A Better Way To List Files In A Directory In Python
This is the function to use:
Code
=
=
=
=
if
]
=
=
=
=
if
]
=
=
return
Code
<<>>
=
Results
[{'extension': 'html',
'full_path': '/Users/alan/Desktop/yttest/index.html',
'name_with_extension': 'index.html',
'name_without_extension': 'index',
'root_dir': '/Users/alan/Desktop/yttest',
'sub_dir': ''}]
_NOTE: This is still a draft in terms of the prose, but the code is tested and working. Still need to deal with hidden files though. Also need to set a flag to not go recursive_
Getting a list of files always feels like a pain. I wrote a JavaScript function a while ago to make it easier. It returns an array with details of the files.
I made a python version that does the same thing. The output look something like this:
Code
[
{
'extension': 'txt',
'full_path': '/Users/alan/list-dir-via-walk/samples/3/a.txt',
'name_with_extension': 'a.txt',
'name_without_extension': 'a',
'root_dir': '/Users/alan/list-dir-via-walk/samples/3',
'sub_dir': ''
},
{
'extension': 'txt',
'full_path': '/Users/alan/list-dir-via-walk/samples/3/3_lower_1/b.txt',
'name_with_extension': 'b.txt',
'name_without_extension': 'b',
'root_dir': '/Users/alan/list-dir-via-walk/samples/3',
'sub_dir': '3_lower_1'
},
{
'extension': 'txt',
'full_path': '/Users/alan/list-dir-via-walk/samples/3/3_lower_1/3_lower_2/c.txt',
'name_with_extension': 'c.txt',
'name_without_extension': 'c',
'root_dir': '/Users/alan/list-dir-via-walk/samples/3',
'sub_dir': '3_lower_1/3_lower_2'
}
]
That makes it easy to get to individual files by name or path, with or without extension.
Here's the code