{"id":470,"date":"2016-03-20T00:22:16","date_gmt":"2016-03-19T16:22:16","guid":{"rendered":"https:\/\/www.techcoil.com\/blog\/?p=470"},"modified":"2018-09-04T22:58:23","modified_gmt":"2018-09-04T14:58:23","slug":"how-to-traverse-all-folders-and-files-within-a-folder-dynamically-in-python-3","status":"publish","type":"post","link":"https:\/\/www.techcoil.com\/blog\/how-to-traverse-all-folders-and-files-within-a-folder-dynamically-in-python-3\/","title":{"rendered":"How to traverse all folders and files within a folder dynamically in Python 3"},"content":{"rendered":"<p>I had this requirement where I need to be able to look into a folder and pick up any configuration files for my Python 3 application. In order to achieve that, I first set an exploratory task to get the Python 3 code for traversing all folders and files within a folder.<\/p>\n<p>For this exploratory task, I had created a script that will traverse the folders and files that are contained within a folder and print out their full paths.<\/p>\n<h3>Python 3 code for traversing all folders and files within a folder dynamically, from bottom to top<\/h3>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nimport os\r\n\r\ndef traverseDir(folderPath):\r\n\r\n    for subFolderRoot, foldersWithinSubFolder, files in os.walk(folderPath, topdown=False):\r\n\r\n        for fileName in files:\r\n            print(os.path.join(subFolderRoot, fileName))\r\n\r\n        for folderNameWithinSubFolder in foldersWithinSubFolder:\r\n            print(os.path.join(subFolderRoot, folderNameWithinSubFolder))\r\n\r\n\r\ntraverseDir('\/sample-dir')\r\n<\/pre>\n<p>In the above script, I defined a function <code>traverseDir<\/code> which will take in the path of the folder which the caller wishes to traverse via the <code>folderPath<\/code> variable.<\/p>\n<p>It then utilises the <code><a href=\"https:\/\/docs.python.org\/3\/library\/os.html#os.walk\" title=\"Python 3 reference for os.walk function\" target=\"_blank\">os.walk<\/a><\/code> function to traverse the contents of the folder specified by <code>folderPath<\/code>. By using <code>topdown=False<\/code>, we tell <code>os.walk<\/code> to traverse the folder tree depth-first. <\/p>\n<p>Each iteration of <code>os.walk<\/code> returns us the path to a subfolder, a list of folders and a list of files within that subfolder. With that, I then:<\/p>\n<ol>\n<li>loop the list of files and print their full path.<\/li>\n<li>loop the list of folders and print their full path.<\/li>\n<\/ol>\n<h3>Sample use case and output<\/h3>\n<h4>A sample file hierarchy<\/h4>\n<p>In order to test whether the Python 3 script is able to traverse all folders and files within a folder dynamically, I created some files and folders with the following hireachical structure:<\/p>\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">\r\n\/sample-dir\r\n--fileA.txt\r\n--folderA\r\n----fileB.txt\r\n----folderC\r\n------fileC.txt\r\n--folderB\r\n----fileD.txt\r\n----folderD\r\n<\/pre>\n<h4>Output from running the Python 3 script (with <code>topdown=False<\/code> supplied to <code>os.walk<\/code>)<\/h4>\n<p>Running the Python 3 script that I had created on \/sample-dir, I would yield the following result:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\n\/sample-dir\/folderA\/folderC\/fileC.txt\r\n\/sample-dir\/folderA\/fileB.txt\r\n\/sample-dir\/folderA\/folderC\r\n\/sample-dir\/folderB\/fileD.txt\r\n\/sample-dir\/folderB\/folderD\r\n\/sample-dir\/fileA.txt\r\n\/sample-dir\/folderA\r\n\/sample-dir\/folderB\r\n<\/pre>\n<h4>Output from running the Python 3 script (with <code>topdown=True<\/code> supplied to <code>os.walk<\/code>)<\/h4>\n<p>Running the Python 3 script on <code>\/sample-dir<\/code> with <code>topdown=True<\/code> I would yield the following result:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\n\/sample-dir\/fileA.txt\r\n\/sample-dir\/folderA\r\n\/sample-dir\/folderB\r\n\/sample-dir\/folderA\/fileB.txt\r\n\/sample-dir\/folderA\/folderC\r\n\/sample-dir\/folderA\/folderC\/fileC.txt\r\n\/sample-dir\/folderB\/fileD.txt\r\n\/sample-dir\/folderB\/folderD\r\n<\/pre>\n\n      <ul id=\"social-sharing-buttons-list\">\n        <li class=\"facebook\">\n          <a href=\"https:\/\/www.facebook.com\/sharer\/sharer.php?u=https%3A%2F%2Fwp.me%2Fp245TQ-7A\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n            <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Facebook.png\" alt=\"Facebook icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"twitter\">\n          <a href=\"https:\/\/twitter.com\/intent\/tweet?text=&url=https%3A%2F%2Fwp.me%2Fp245TQ-7A&via=Techcoil_com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Twitter.png\" alt=\"Twitter icon\"> Tweet\n          <\/a>\n        <\/li>\n        <li class=\"linkedin\">\n          <a href=\"https:\/\/www.linkedin.com\/shareArticle?mini=1&title=&url=https%3A%2F%2Fwp.me%2Fp245TQ-7A&source=https:\/\/www.techcoil.com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/linkedin.png\" alt=\"Linkedin icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"pinterest\">\n          <a href=\"https:\/\/pinterest.com\/pin\/create\/button\/?url=https%3A%2F%2Fwww.techcoil.com%2Fblog%2Fwp-json%2Fwp%2Fv2%2Fposts%2F470&description=\" class=\"pin-it-button\" target=\"_blank\" role=\"button\" rel=\"nofollow\" count-layout=\"horizontal\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Pinterest.png\" alt=\"Pinterest icon\"> Save\n          <\/a>\n        <\/li>\n      <\/ul>\n    ","protected":false},"excerpt":{"rendered":"<p>I had this requirement where I need to be able to look into a folder and pick up any configuration files for my Python 3 application. In order to achieve that, I first set an exploratory task to get the Python 3 code for traversing all folders and files within a folder.<\/p>\n<p>For this exploratory task, I had created a script that will traverse the folders and files that are contained within a folder and print out their full paths.<\/p>\n","protected":false},"author":1,"featured_media":1244,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"advanced_seo_description":"","jetpack_seo_html_title":"","jetpack_seo_noindex":false,"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":true,"_jetpack_newsletter_tier_id":0,"footnotes":""},"categories":[375],"tags":[95,236,226,233],"jetpack_featured_media_url":"https:\/\/www.techcoil.com\/blog\/wp-content\/uploads\/Python-Logo.gif","jetpack_shortlink":"https:\/\/wp.me\/p245TQ-7A","jetpack-related-posts":[],"jetpack_likes_enabled":true,"jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/470"}],"collection":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/comments?post=470"}],"version-history":[{"count":0,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/470\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media\/1244"}],"wp:attachment":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media?parent=470"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/categories?post=470"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/tags?post=470"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}