{"id":87061,"date":"2023-04-04T10:42:08","date_gmt":"2023-04-04T05:12:08","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=87061"},"modified":"2023-04-04T10:42:08","modified_gmt":"2023-04-04T05:12:08","slug":"python-directories","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/python-directories\/","title":{"rendered":"Python Directories"},"content":{"rendered":"<p>In Python, a directory, also known as a folder, is a way to organize and store files on a computer. The os module in Python provides several functions for interacting with the file system, including creating, removing, and manipulating directories. These functions allow for easy and efficient management of directories in a Python program.<\/p>\n<p>Using these functions, one can easily manage directories in a Python program, for example, one can create, remove and list the directory, change the current working directory and many more. These functions are very useful when dealing with file management in python.<\/p>\n<h3>List of some common methods for working with directories in Python<\/h3>\n<p><strong>1. os.mkdir(path): <\/strong>This method creates a new directory with the given path.<\/p>\n<p><b><b>Example:<\/b><\/b><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import os\n\nos.mkdir(\"test\")\nprint(os.listdir())\n# Output: ['test']\n<\/pre>\n<p><b>2. os.makedirs(path): <\/b>This method creates a new directory along with all its parent directories.<\/p>\n<p><b>Example:<\/b><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import os\n\nos.makedirs(\"test1\/test2\")\nprint(os.listdir())\n# Output: ['test1']\nprint(os.listdir(\"test1\"))\n# Output: ['test2']\n<\/pre>\n<p><b>3. os.rmdir(path): <\/b>This method removes an empty directory with the given path.<\/p>\n<p><b>Example:<\/b><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import os\n\nos.mkdir(\"test\")\nprint(os.listdir())\n# Output: ['test']\nos.rmdir(\"test\")\nprint(os.listdir())\n# Output: []\n<\/pre>\n<p><b>4. os.removedirs(path): <\/b>This method removes a directory and all its parent directories if they are empty.<\/p>\n<p><b><b>Example:<\/b><\/b><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import os\n\nos.makedirs(\"test1\/test2\")\nprint(os.listdir())\n# Output: ['test1']\nos.removedirs(\"test1\/test2\")\nprint(os.listdir())\n# Output: []\n<\/pre>\n<p><b>5. os.chdir(path): <\/b>This method changes the current working directory to the given path.<\/p>\n<p><b><b>Example:<\/b><\/b><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import os\n\nos.mkdir(\"test\")\nos.chdir(\"test\")\nprint(os.getcwd())\n# Output: \/path\/to\/current\/directory\/test\n<\/pre>\n<p><b>6. os.getcwd(): <\/b>This method returns the current working directory as a string.<\/p>\n<p><b>Example:<\/b><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import os\n\nprint(os.getcwd())\n# Output: \/path\/to\/current\/directory\n<\/pre>\n<p><b><b>7. os.listdir(path): <\/b><\/b>This method lists the files and directories in the given path. If the path is not provided, it will list the files and directories in the current working directory.<\/p>\n<p><b><b>Example:<\/b><\/b><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import os\n\nos.mkdir(\"test\")\nprint(os.listdir())\n# Output: ['test']\n<\/pre>\n<p><b>8. os.path.exists(path): <\/b>This method returns a Boolean indicating whether the provided path points to an existing file or directory.<\/p>\n<p><b>Example:<\/b><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import os\n\nos.mkdir(\"test\")\nprint(os.path.exists(\"test\"))\n# Output: True\nprint(os.path.exists(\"non_existent_dir\"))\n# Output: False\n<\/pre>\n<p><strong>9. os.path.isdir(path):<\/strong> This method returns a Boolean indicating whether the provided path points to an existing directory.<\/p>\n<p><strong><strong>Example:<\/strong><\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import os\n\nos.mkdir(\"test\")\nprint(os.path.isdir(\"test\"))\n# Output: True\nprint(os.path.isdir(\"non_existent_dir\"))\n# Output: False\n<\/pre>\n<p><strong>10. os.path.abspath(path):<\/strong> This method returns the absolute path of the provided path.<br \/>\n<strong><strong>Example:<\/strong><\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import os\n\nprint(os.path.abspath(\"test\"))\n# Output: \/path\/to\/current\/directory\/test\n<\/pre>\n<p><strong>11. os.path.basename(path):<\/strong> This method returns the base name of the provided path.<\/p>\n<p><strong><strong>Example:<\/strong><\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import os\n\nprint(os.path.basename(\"\/path\/to\/file.txt\"))\n# Output: file.txt\n<\/pre>\n<p><strong>12. os.path.dirname(path):<\/strong> This method returns the directory name of the provided path.<\/p>\n<p><strong><strong>Example:<\/strong><\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import os\n\nprint(os.path.dirname(\"\/path\/to\/file.txt\"))\n# Output: \/path\/to\n<\/pre>\n<p><strong>13. os.path.split(path):<\/strong> This method splits the provided path into a tuple containing the directory name and the base name.<\/p>\n<p><strong><strong>Example:<\/strong><\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import os\n\nprint(os.path.split(\"\/path\/to\/file.txt\"))\n# Output: ('\/path\/to', 'file.txt')\n<\/pre>\n<p><strong>14. os.path.splitext(path):<\/strong> This method splits the provided path into a tuple containing the file name and the file extension.<\/p>\n<p><strong><strong>Example:<\/strong><\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import os\n\nprint(os.path.splitext(\"\/path\/to\/file.txt\"))\n# Output: ('\/path\/to\/file', '.txt')\n<\/pre>\n<p><strong>15. os.path.getsize(path):<\/strong> This method returns the size of the file in bytes for the provided path.<\/p>\n<p><strong><strong>Example:<\/strong><\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import os\n\nwith open(\"test.txt\", \"w\") as f:\n    f.write(\"test\")\nprint(os.path.getsize(\"test.txt\"))\n# Output: 4\n<\/pre>\n<p><strong>16. os.path.getmtime(path): <\/strong>This method returns the last modification time of the provided path as a timestamp.<\/p>\n<p><strong><strong>Example:<\/strong><\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import os\nimport time\n\nwith open(\"test.txt\", \"w\") as f:\n    f.write(\"test\")\ntime.sleep(2)\nwith open(\"test.txt\", \"a\") as f:\n    f.write(\" more test\")\nprint(os.path.getmtime(\"test.txt\"))\n# Output: timestamp\n<\/pre>\n<p><strong>17. os.path.normpath(path):<\/strong> This method returns a normalized pathname.<\/p>\n<p><strong><strong>Example:<\/strong><\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import os\n\nprint(os.path.normpath(\"\/path\/to\/..\/.\/file.txt\"))\n# Output: \/path\/file.txt\n<\/pre>\n<h3>How directories can be used in Python<\/h3>\n<h4>1. Recursively traversing a directory structure:<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import os\n\ndef traverse_directory(directory):\n    for root, dirs, files in os.walk(directory):\n        print(f\"At directory {root}:\")\n        for d in dirs:\n            print(f\"    Found directory: {d}\")\n        for f in files:\n            print(f\"    Found file: {f}\")\n\ntraverse_directory(\".\")\n<\/pre>\n<h4>2. Creating a backup of a directory:<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import os\nimport shutil\n\ndef create_backup(src, dest):\n    shutil.copytree(src, dest)\n\ncreate_backup(\"original_dir\", \"backup_dir\")\n<\/pre>\n<h4>3. Compressing a directory:<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import os\nimport zipfile\n\ndef compress_directory(directory):\n    with zipfile.ZipFile(\"archive.zip\", \"w\") as archive:\n        for root, dirs, files in os.walk(directory):\n            for file in files:\n                archive.write(os.path.join(root, file))\n\ncompress_directory(\"directory_to_compress\")\n<\/pre>\n<h4>4. Searching for a file in a directory:<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import os\n\ndef search_file(directory, file_name):\n    for root, dirs, files in os.walk(directory):\n        if file_name in files:\n            return os.path.join(root, file_name)\n    return None\n\nprint(search_file(\".\", \"file.txt\"))\n<\/pre>\n<h4>5. Renaming a directory:<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import os\n\nos.rename(\"old_dir_name\", \"new_dir_name\")\n<\/pre>\n<h4>6. Creating a directory with specific permissions:<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import os\n\nos.makedirs(\"test\", mode=0o700)\n<\/pre>\n<h4>7. Creating a temporary directory:<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import tempfile\n\ntemp_dir = tempfile.TemporaryDirectory()\nprint(temp_dir.name)\n# Output: \/path\/to\/temp\/directory\n<\/pre>\n<h4>8. Listing all the subdirectories in a directory:<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import os\n\nsub_directories = [d for d in os.listdir() if os.path.isdir(d)]\nprint(sub_directories)\n<\/pre>\n<h4>9. Counting the number of files in a directory:<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import os\n\ndef count_files(directory):\n    return len([f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))])\n\nprint(count_files(\".\"))\n<\/pre>\n<h3>Conclusion<\/h3>\n<p>In this article by TechVidvan, we can conclude by saying that directories, also known as folders, are an important aspect of file management in Python. The os module in Python provides a wide range of functions for interacting with the file system, including creating, removing, and manipulating directories. These functions allow for easy and efficient management of directories in a Python program. With the use of the os module and other libraries, directories can be used for a variety of tasks such as file management, backup, compression, traversing, and many more.<\/p>\n<p>Python&#8217;s os module provides a simple and easy-to-use interface to interact with the file system and directories. It allows developers to perform various operations such as creating, renaming, deleting, and traversing directories. With the help of the os module and other libraries, Python can be used for a wide range of file management tasks, making it a powerful tool for managing and organizing files and directories.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In Python, a directory, also known as a folder, is a way to organize and store files on a computer. The os module in Python provides several functions for interacting with the file system,&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":87338,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1053],"tags":[4920],"class_list":["post-87061","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","tag-python-directories"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Python Directories - TechVidvan<\/title>\n<meta name=\"description\" content=\"Directories are an important aspect of file management in Python. See common methods for working with directories in Python\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/python-directories\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Python Directories - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Directories are an important aspect of file management in Python. See common methods for working with directories in Python\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/python-directories\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2023-04-04T05:12:08+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2023\/02\/python-directory.webp\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/webp\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Python Directories - TechVidvan","description":"Directories are an important aspect of file management in Python. See common methods for working with directories in Python","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/techvidvan.com\/tutorials\/python-directories\/","og_locale":"en_US","og_type":"article","og_title":"Python Directories - TechVidvan","og_description":"Directories are an important aspect of file management in Python. See common methods for working with directories in Python","og_url":"https:\/\/techvidvan.com\/tutorials\/python-directories\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2023-04-04T05:12:08+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2023\/02\/python-directory.webp","type":"image\/webp"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/python-directories\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-directories\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Python Directories","datePublished":"2023-04-04T05:12:08+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-directories\/"},"wordCount":627,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-directories\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2023\/02\/python-directory.webp","keywords":["Python Directories"],"articleSection":["Python Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/python-directories\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/python-directories\/","url":"https:\/\/techvidvan.com\/tutorials\/python-directories\/","name":"Python Directories - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-directories\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-directories\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2023\/02\/python-directory.webp","datePublished":"2023-04-04T05:12:08+00:00","description":"Directories are an important aspect of file management in Python. See common methods for working with directories in Python","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-directories\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/python-directories\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/python-directories\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2023\/02\/python-directory.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2023\/02\/python-directory.webp","width":1200,"height":628,"caption":"python directory"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/python-directories\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Python Directories"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/87061","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=87061"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/87061\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/87338"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=87061"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=87061"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=87061"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}