A Better Way To List Files In A Directory In Python
Check this out before tyring the below
https://docs.python.org/3.9/library/os.html?highlight=os%20walk#os.walk
Using os.walk()
=
=
Output:
walk-directory-test/1.txt
walk-directory-test/charlie/4.txt
walk-directory-test/charlie/delta/5.txt
walk-directory-test/alfa/2.txt
walk-directory-test/alfa/bravo/3.txt
OLD NOTES BELOW
This was the original version of the script that I made before finding os.walk()
.
This is the function to use:
=
=
=
=
=
=
=
=
=
=
return
<<>>
=
Output:
[{'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:
[
{
'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.
-- end of line --