{"id":1102,"date":"2016-04-12T12:46:10","date_gmt":"2016-04-12T12:46:10","guid":{"rendered":"http:\/\/frowningbear.com\/blog\/?p=1102"},"modified":"2016-04-12T12:46:10","modified_gmt":"2016-04-12T12:46:10","slug":"python-working-with-directories-reference","status":"publish","type":"post","link":"https:\/\/frowningbear.com\/codebase\/2016\/04\/12\/python-working-with-directories-reference\/","title":{"rendered":"Python Working with Directories Reference"},"content":{"rendered":"<p>My notes compiled on the topic of working with directories, navigating folders and listing files etc.<br \/>\n<!--more--><\/p>\n<pre class=\"wrap:true lang:default decode:true \" title=\"Working with Directories\" >#Use os.listdir (or os.scandir in &gt;= 3.5) to list items in a single directory, use os.walk (which uses os.listdir or os.scandir in &gt;= 3.5) to list items in a directory tree.\n\n#Using os.walk for only one directory is not as efficient as just using the function it uses internally to do that job.\n\n#os.listdir(path='.')\n\n#os.listdir returns a list of names (files and directories) in a given path\n\n#default value for path when you call os.listdir() is '.'\n\n#so os.listdir() and os.listdir('.') do the same thing, grabbing the current directory\n\n#path can be specified as either str or bytes. If path is bytes, the filenames returned will also be bytes; in all other circumstances the filenames returned will be str.\n\n#What does it mean when the docs say that os.listdir specifically excludes '.' and '..' even if they are present in the directory?\n\n#That concerns the returned values. In UNIX filesystems, every directory has . and .. entries, where . refers to the current directory, and .. to the parent directory. These entries will not be included in the list returned by os.listdir.\n\n#The scandir() function returns directory entries along with file attribute information, giving better performance for many common use cases.\n\n#glob.glob is a wrapper around listdir\n\nimport os\n\n#os.getcwd()\n#os.chdir(\"subFolder\")\n#os.mkdir(\"My New Folder\")\n#os.rename(\"My New Folder\", \"My New Folder renamed\")\n\n#The listdir function takes a pathname and returns a list of the contents of the directory.\nprint(os.listdir(\"c:\\\\Files\\\\\"))\n\n# another way\nmyfiles = os.listdir(\"c:\\\\Files\\\\\")\nprint(myfiles)\n\n#same thing but using variables.\ndirname = \"c:\\\\Files\\\\\"\nprint(os.listdir(dirname))\n\n#all three list the current directory\nprint(os.listdir())\nprint(os.listdir(\".\"))\nprint(os.listdir(\".\/\"))\n\n# print contents of a sub folder in current directory\nprint(os.listdir(\"subFolder\"), \"\\n\")\n\n#output a list\nprint(os.listdir(\".\"))\n\n#loop over each item in the list\nfor name in os.listdir():\n    print(name)\n\n#or place in variable first\nfilelist = os.listdir()\n\n#just print the variable contents\nprint(filelist)\n\n#loop over each item in the variable's list\nfor name in filelist:\n    print(name)\n\n#its common to use os.path.join to get full paths\nfor entry in os.listdir(\".\"):\n    path = os.path.join(\".\", entry)\n    print(path)\n\n#use os.path.isdir() to filter out directories, printing only files\nfor name in filelist:\n    if os.path.isdir(name):\n        continue\n    print(name)\n\n#os.path.isfile() is an alternative, testing for 'fileness' instead\n\n#so alternatively...\n\n#only files\nfor x in os.listdir(\".\"):\n    if os.path.isfile(x):\n        print(x)\n#or\n\n#only directories\nfor x in os.listdir(\".\"):\n    if os.path.isdir(x):\n        print(x)\n\n#a list comprehension using os.path.isfile() to return list of filenames only:\nfiles = [f for f in os.listdir(\".\") if os.path.isfile(os.path.join(\".\", f))]\nfor file in files:\n    print(file)\n\n#another alternative using filter function\nfiles = filter(os.path.isfile, os.listdir(os.curdir))\n\nprint(type(files)) #&lt;class 'filter'&gt;\n\nprint(files) #&lt;filter object at 0x032C1BD0&gt;\n\n#loop over the filter object\nfor file in files:\n    print(file)\n\n#filter filetypes by using endswith()\nfor file in os.listdir(\".\/\"):\n    if file.endswith(\".jpg\"):\n        print(file)\n\n#using fnmatch we can filter files by type\nimport fnmatch\nlistOfFiles = os.listdir('.')  \npattern = \"*.py\"  \nfor entry in listOfFiles:  \n    if fnmatch.fnmatch(entry, pattern):\n            print(entry)\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>My notes compiled on the topic of working with directories, navigating folders and listing files etc.<\/p>\n","protected":false},"author":2,"featured_media":1098,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[14],"tags":[],"class_list":["post-1102","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python"],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/posts\/1102","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/comments?post=1102"}],"version-history":[{"count":0,"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/posts\/1102\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/"}],"wp:attachment":[{"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/media?parent=1102"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/categories?post=1102"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/tags?post=1102"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}