how to search if a file is present in a folder or not

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • learnerofpython
    New Member
    • Nov 2006
    • 14

    how to search if a file is present in a folder or not

    Hi!
    Can any1 help me out.
    Actually i wanted to search if a file is present in a folder using python script.
    The file is under creation and i want to keep on searching in that folder if the file has been successfully created or not.please help me!!!
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Originally posted by learnerofpython
    Hi!
    Can any1 help me out.
    Actually i wanted to search if a file is present in a folder using python script.
    The file is under creation and i want to keep on searching in that folder if the file has been successfully created or not.please help me!!!
    Change the drive, directories and file name to match your case and try this:
    Code:
    import os
    
    def fileChk(file_name):
        try:
            f = open(file_name, "r")
            f.close()
            return True
        except IOError, e:
            # unable to open file
            return False
    
    dir_name = (os.path.join('C:\\', 'SDS2_7.0', 'macro'))
    file_name = ("your_file.dat")
    if fileChk(os.path.join(dir_name, file_name)):
        print "Success!"
    else:
        print "File does not exist"

    Comment

    • ghostdog74
      Recognized Expert Contributor
      • Apr 2006
      • 511

      #3
      check out os.path.exists( ) . It should do what you want.

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        Originally posted by ghostdog74
        check out os.path.exists( ) . It should do what you want.
        Good point ghostdog74. Thanks!
        Code:
        if os.path.exists(os.path.join(dir_name, file_name)):
            print "Success!"
        else:
            print "File does not exist"

        Comment

        Working...