[Tut] The Most Pythonic Way to Check if a File Exists in Python - Printable Version +- Sick Gaming (https://www.sickgaming.net) +-- Forum: Programming (https://www.sickgaming.net/forum-76.html) +--- Forum: Python (https://www.sickgaming.net/forum-83.html) +--- Thread: [Tut] The Most Pythonic Way to Check if a File Exists in Python (/thread-95801.html) |
[Tut] The Most Pythonic Way to Check if a File Exists in Python - xSicKxBot - 06-20-2020 The Most Pythonic Way to Check if a File Exists in Python <div><figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"> <div class="wp-block-embed__wrapper"> <div class="ast-oembed-container"><iframe 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> </div> </figure> <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> <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: print(os.path.exists('main.py')) # True # Check for non-existing file: print(os.path.exists('folder/nonexistent.py')) # False</pre> <figure class="wp-block-image size-large is-resized"><img 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="(max-width: 768px) 100vw, 768px" /></figure> <hr class="wp-block-separator"/> <p>The web is full of guides that show you <em>“the X most common ways to check if a file exists in Python”</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’s hard to extract the precise method—they are far too long and the content is fluffy and lengthy.</p> <p><strong><em>If you’re like me, you just want to know the best and most Pythonic way to check if a file exists, right?</em></strong></p> <p>In this 2-min tutorial, I’ll give you a to-the-point solution that you can apply right away! So, let’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> <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> <p><strong>Example</strong>: Say, you’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> <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' # Method returns True filename_2 = 'my/directory/non-existing-file.txt' # Method returns False</pre> <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’t exist).</p> <p><strong>Solution</strong>: Without further ado, let’s look at the most Pythonic way to check, in your script, if a file exists.</p> <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 >>> os.path.exists('file-that-exists.txt') True >>> os.path.exists('my/directory/non-existing-file.txt') False</pre> <p>You can try this yourself in our interactive code shell:</p> <p> <iframe 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> <p><em><strong>Exercise</strong>: Run the code. What’s the output? Create the non-existing file so that the second method call returns True!</em></p> <h2>A Pythonic Excursion</h2> <p>You now know how to check if a file exists (and what’s the most Pythonic way of doing so). But there’s a caveat! You actually shouldn’t do it. </p> <p>The reason is that you probably use your file existence checking mechanism to do something along those lines (only pseudocode):</p> <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: if file_exists(): open_file()</pre> <p>The problem is that your<a href="https://blog.finxter.com/python-crash-course/" target="_blank" rel="noreferrer noopener"> Python program</a> doesn’t have exclusive control of the file on your operating system. You don’t know what’s happening between checking if the file exists and opening the file. </p> <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> <p>For example, your program may find that the file exists. Another thread may then delete the file, so it doesn’t exist anymore. Then, your program executes the second line <code>open_file()</code> working on a non-existent file!</p> <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’t exist, Python throws an exception which you catch in your enclosing block.</p> <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() except FileNotFoundError: print('File does not exist')</pre> <p>This is far better—if you want to avoid any output if the file doesn’t exist, just do nothing in the except statement:</p> <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() except FileNotFoundError: None</pre> <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> <h2>Where to Go From Here?</h2> <p>Enough theory, let’s get some practice!</p> <p>To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?</p> <p><strong>Practice projects is how you sharpen your saw in coding!</strong></p> <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> <p>Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.</p> <p>Join my free webinar <a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">“How to Build Your High-Income Skill Python”</a> and watch how I grew my coding business online and how you can, too—from the comfort of your own home.</p> <p><a href="https://blog.finxter.com/webinar-freelancer/" target="_blank" rel="noreferrer noopener">Join the free webinar now!</a></p> </div> https://www.sickgaming.net/blog/2020/06/19/the-most-pythonic-way-to-check-if-a-file-exists-in-python/ |