{"id":114359,"date":"2020-06-19T09:59:20","date_gmt":"2020-06-19T09:59:20","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=9905"},"modified":"2020-06-19T09:59:20","modified_gmt":"2020-06-19T09:59:20","slug":"the-most-pythonic-way-to-check-if-a-file-exists-in-python","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/06\/19\/the-most-pythonic-way-to-check-if-a-file-exists-in-python\/","title":{"rendered":"The Most Pythonic Way to Check if a File Exists in Python"},"content":{"rendered":"<figure class=\"wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\">\n<div class=\"wp-block-embed__wrapper\">\n<div class=\"ast-oembed-container\"><iframe loading=\"lazy\" title=\"The Most Pythonic Way to Check if a File Exists in Python\" width=\"1400\" height=\"788\" src=\"https:\/\/www.youtube.com\/embed\/MmbkRG4Lk5o?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe><\/div>\n<\/div>\n<\/figure>\n<p class=\"has-background has-luminous-vivid-amber-background-color\">The method <code>os.path.exists('file.txt')<\/code> returns <code>True<\/code> if the file <code>'file.txt'<\/code> exists, and <code>False<\/code> otherwise. To use it, import the <code>os<\/code> module first with <code>import os<\/code>. If you want to check if a file exists at a given path, use the standard path notation <code>'\/file\/at\/path\/file.txt'<\/code> as a prefix.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import os # Check for existing file:\nprint(os.path.exists('main.py'))\n# True # Check for non-existing file:\nprint(os.path.exists('folder\/nonexistent.py'))\n# False<\/pre>\n<figure class=\"wp-block-image size-large is-resized\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/fileexists-1024x576.jpg\" alt=\"The Most Pythonic Way to Check if a File Exists in Python\" class=\"wp-image-9916\" width=\"768\" height=\"432\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/fileexists-scaled.jpg 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/fileexists-300x169.jpg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/fileexists-768x432.jpg 768w\" sizes=\"auto, (max-width: 768px) 100vw, 768px\" \/><\/figure>\n<hr class=\"wp-block-separator\"\/>\n<p>The web is full of guides that show you <em>&#8220;the X most common ways to check if a file exists in Python&#8221;<\/em> (examples: <a rel=\"noreferrer noopener\" href=\"https:\/\/dbader.org\/blog\/python-check-if-file-exists\" target=\"_blank\">here<\/a>, <a rel=\"noreferrer noopener\" href=\"https:\/\/www.guru99.com\/python-check-if-file-exists.html\" target=\"_blank\">here<\/a>, and <a rel=\"noreferrer noopener\" href=\"https:\/\/stackoverflow.com\/questions\/82831\/how-do-i-check-whether-a-file-exists-without-exceptions\" target=\"_blank\">here<\/a>). But when reading over them, I found that it&#8217;s hard to extract the precise method&#8212;they are far too long and the content is fluffy and lengthy.<\/p>\n<p><strong><em>If you&#8217;re like me, you just want to know the best and most Pythonic way to check if a file exists, right?<\/em><\/strong><\/p>\n<p>In this 2-min tutorial, I&#8217;ll give you a to-the-point solution that you can apply right away! So, let&#8217;s dive into the precise problem formulation and its most <a href=\"https:\/\/blog.finxter.com\/python-join-list-in-reverse-order\/\" target=\"_blank\" rel=\"noreferrer noopener\">Pythonic <\/a>way to solve it.<\/p>\n<p><strong>Problem<\/strong>: Given a filename and the <a href=\"https:\/\/blog.finxter.com\/python-join-list-as-path\/\" target=\"_blank\" rel=\"noreferrer noopener\">path <\/a>information. Check if a file with the filename exists at a specified path, or not. The return value should be a Boolean value (<code>True<\/code>, if the file exists, and <code>False<\/code> otherwise).<\/p>\n<p><strong>Example<\/strong>: Say, you&#8217;ve got the following filenames as <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/daily-python-puzzle-string-formatting\/\" target=\"_blank\">strings, <\/a>including path information (as string prefix).<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">filename_1 = 'file-that-exists.txt'\n# Method returns True filename_2 = 'my\/directory\/non-existing-file.txt' # Method returns False<\/pre>\n<p>You want a method that returns <code>True<\/code> for the first filename (the file that exists) and <code>False<\/code> for the second filename (the file that doesn&#8217;t exist).<\/p>\n<p><strong>Solution<\/strong>: Without further ado, let&#8217;s look at the most Pythonic way to check, in your script, if a file exists.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> import os\n>>> os.path.exists('file-that-exists.txt')\nTrue\n>>> os.path.exists('my\/directory\/non-existing-file.txt')\nFalse<\/pre>\n<p>You can try this yourself in our interactive code shell:<\/p>\n<p> <iframe loading=\"lazy\" height=\"400px\" width=\"100%\" src=\"https:\/\/repl.it\/@finxter\/checkfileexists?lite=true\" scrolling=\"no\" frameborder=\"no\" allowtransparency=\"true\" allowfullscreen=\"true\" sandbox=\"allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals\"><\/iframe> <\/p>\n<p><em><strong>Exercise<\/strong>: Run the code. What&#8217;s the output? Create the non-existing file so that the second method call returns True!<\/em><\/p>\n<h2>A Pythonic Excursion<\/h2>\n<p>You now know how to check if a file exists (and what&#8217;s the most Pythonic way of doing so). But there&#8217;s a caveat! You actually shouldn&#8217;t do it. <\/p>\n<p>The reason is that you probably use your file existence checking mechanism to do something along those lines (only pseudocode):<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># PSEUDOCODE:\nif file_exists(): open_file()<\/pre>\n<p>The problem is that your<a href=\"https:\/\/blog.finxter.com\/python-crash-course\/\" target=\"_blank\" rel=\"noreferrer noopener\"> Python program<\/a> doesn&#8217;t have exclusive control of the file on your operating system. You don&#8217;t know what&#8217;s happening between checking if the file exists and opening the file. <\/p>\n<p><strong><em>In other words: this method is not thread-safe. <\/em><\/strong>Multiple threads may access the same file, which can lead to strange behaviors.<\/p>\n<p>For example, your program may find that the file exists. Another thread may then delete the file, so it doesn&#8217;t exist anymore. Then, your program executes the second line <code>open_file()<\/code> working on a non-existent file!<\/p>\n<p>To resolve this issue, you should just open the file right away and enclose it in a try\/except block. If the file doesn&#8217;t exist, Python throws an exception which you catch in your enclosing block.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">try: f = open('file.txt') # Do something with file f.close()\nexcept FileNotFoundError: print('File does not exist')<\/pre>\n<p>This is far better&#8212;if you want to avoid any output if the file doesn&#8217;t exist, just do nothing in the except statement:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">try: f = open('nonexistent_file.py') print(f) f.close()\nexcept FileNotFoundError: None<\/pre>\n<p>I hope you liked the small tutorial. If you want to improve your Python skills continuously (and for free), check out my <a href=\"https:\/\/blog.finxter.com\/subscribe\/\" target=\"_blank\" rel=\"noreferrer noopener\">email computer science academy<\/a> (including free cheat sheets)!<\/p>\n<h2>Where to Go From Here?<\/h2>\n<p>Enough theory, let\u2019s get some practice!<\/p>\n<p>To become successful in coding, you need to get out there and solve real problems for real people. That\u2019s how you can become a six-figure earner easily. And that\u2019s how you polish the skills you really need in practice. After all, what\u2019s the use of learning theory that nobody ever needs?<\/p>\n<p><strong>Practice projects is how you sharpen your saw in coding!<\/strong><\/p>\n<p>Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?<\/p>\n<p>Then become a Python freelance developer! It\u2019s the best way of approaching the task of improving your Python skills\u2014even if you are a complete beginner.<\/p>\n<p>Join my free webinar <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/webinar-freelancer\/\" target=\"_blank\">\u201cHow to Build Your High-Income Skill Python\u201d<\/a> and watch how I grew my coding business online and how you can, too\u2014from the comfort of your own home.<\/p>\n<p><a href=\"https:\/\/blog.finxter.com\/webinar-freelancer\/\" target=\"_blank\" rel=\"noreferrer noopener\">Join the free webinar now!<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>The method os.path.exists(&#8216;file.txt&#8217;) returns True if the file &#8216;file.txt&#8217; exists, and False otherwise. To use it, import the os module first with import os. If you want to check if a file exists at a given path, use the standard path notation &#8216;\/file\/at\/path\/file.txt&#8217; as a prefix. import os # Check for existing file: print(os.path.exists(&#8216;main.py&#8217;)) # [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-114359","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/114359","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=114359"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/114359\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=114359"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=114359"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=114359"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}