check if a file is open in Python

check if a file is open in Python

Asked on January 8, 2019 in Excel.
Add Comment


  • 3 Answer(s)

          While writing to the file, then close it , so conceited that the user can open it in file. So need to check that the file is not still open in Excel, before re-opening it for append/write operations.

    Try this code :

    try:
        myfile = open("myfile.csv", "r+") # or "a+", whatever you need
    except IOError:
        print "Could not open file! Please close Excel!"
     
    with myfile:
        do_stuff()
    
    Answered on January 8, 2019.
    Add Comment

    The best way is to use the file object attribute “closed”

    Use this code :

    f = open('file.py')
    if f.closed:
       print 'file is closed'
    

    Try this useful link :
    http://docs.python.org/2.4/lib/bltin-file-objects.html

    Answered on January 8, 2019.
    Add Comment

    Here the solution for check if a file is open in Python :

             The alternative way is rename the file or directory including the file temporarily, after this rename it back.

    Follow this code :

    import os
    try:
        os.rename('file.xls', 'tempfile.xls')
        os.rename('tempfile.xls', 'file.xls')
    except OSError:
        print('File is still open.')
    
    Answered on January 8, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.