Home python How to check the existence of a file?

How to check the existence of a file?




How to check the existence of a file on a specific path using Python?

Answer 1, Authority 100%

file_path = "path / to / file.txt"

To check the existence of a specified path, use the OS.path.exists function:

import os.path
os.path.exists (File_Path)

But it will return the true and for the file and for the directory.

os.path.isfile check for the presence of a file.

Answer 2, Authority 46%

briefly : instead of if exists (): Open () Use just OPEN () .

If the check is needed to execute any file with the file, it is better to directly perform this operation and catch the possible errors (assuming that you want to process on the same level of errors):

#! / usr / bin / env python
# - * - Coding: UTF-8 - * -
  File = Open ('input.txt')
Except Ioerror AS E:
  Print (U'Ne managed to open the file ')
  With file:
    Print (U'Deight Something with the file ')

Pre-check anyway does not ensure that the file will still exist later and still have to process errors.

Python is often preferred “It’s easier to ask for forgiveness than permissions” (“IT IS Easier to Ask for Forgiveness Than Permission “- EAFP ) approach instead of “Look Before You Leap.” more common in with .

Answers to comments:

  1. where the Finally block in which you closes the flow

Finally do not need here. If the code got into Except block, the file is not open – there is nothing to close. In Else branch, where the file is open, with file: The design always closes the file when exiting the block (normal or when the exception occurred).

  1. Try-EXEPT-ELSE Design is considered poorly readable.

Usually try / except is not used at the same level, that is, the code is used simply:

with open ('input.txt') AS File:
  Print (U'Deight Something with the file ')

and Possible exceptions above the stack are processed . But if you want to handle an error in open () at the same level, then you must use try / except (open () signals errors using exceptions).

  1. every time there is no file, you call an interruption of the OS (the exclusion processing mechanism is built) on its own, is it too racking?

Exceptions are thrown in case of error in Python, you want it or not. Here is Implementation os.path.exists () from the standard library :

Def Exists (Path):
    OS.Stat (Path)
  Except OSERROR:
    Return False.
  Return True.

In fact, using Open () directly, not if exists (): Open () We Reduce Number of system calls.

  1. Your code took 7 lines, is it better to charge this task with the OS.path.exists command (path_to_file) in a pair of lines?

Code length that does not work does not matter. Once again: Call OS.path.exists () does not guarantee that the file exists when you try to call OPEN () later: you still have to handle errors.

It is worth mentioning that if the absence of a file is not an error in your case (expected by the program), then it is quite possible to use os.path.exists () or its analogs to emphasize the likelihood of the absence of a file for the reader code (but since later opening the file may still fail, this does not free the code from adding error handling appropriate for your task, such as the try / except above).

Answer 3, authority 19%

import os
if os.path.exists (path_to_file):
  # file exists
  # file does not exist

Answer 4, authority 8%

import os
file_path = "path / to / file.txt"
if os.access (file_path, os.F_OK) == True:
      print ("File exists")

Answer 5, authority 8%

As of Python 3.5, double backslash is used between directories

import os
if os.path.exists ("Folder_name \\ Folder_name \\ anytext.txt"):
   print ("File found")
   print ("File not found")

Instead of the print function, you can use any other action – whatever you like)

Answer 6

  print ('Txt-File has been opened!')
  file = open ('file.txt', 'r')
except OSError:
  print ('Txt-file created!')
  file = open ('file.txt', 'w')

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions