Python close files another user may have open

Viewed 61

I need to write to a file that another user may have open. So I think I need a way to try to write to it and if it fails, close the file for all users, then write to it again. Is there a way within Python to do this?

with open(biFile, 'w') as consolidate:
        outputData.to_csv(consolidate, header=True, index=False)

The error I get sometimes is:

PermissionError                           Traceback (most recent call last)
<ipython-input-53-6a5da56e94fb> in <module>()
    373             consolidateDate = consolidateDate + datetime.timedelta(days=32)
    374             consolidateDate = consolidateDate.replace(day=1)
--> 375     with open(biFile, 'w') as consolidate:
    376         outputData.to_csv(consolidate, header=True, index=False)
    377     #=================================================================================

PermissionError: [Errno 13] Permission denied: '\\\\SERVERNAME\\FOLDERNAME\\File.csv'

My initial thought is to simply skip writing to this file if it is open. The script runs every hour so not a huge deal. But a co-worker has just told me about a script one of our interns wrote once that will check if someone has a file open, and if it is not closed within 3 minutes, the script will close it. That same functionality here would be great.

I also thought about making the file read-only to everyone except the user running this script but it will eventually be run at a server level and I am not sure how fond I am of robots being the sole owner of files on our shared drive.

1 Answers

I have gotten around the problem by simply skipping the write if it fails. This script runs hourly so that is not a big deal until a better answer presents itself.

    tryCount = 0
    while tryCount < 5:
        try:
            with open(biFile, 'w') as consolidate:
                outputData.to_csv(consolidate, header=True, index=False)
            tryCount = 5
        except:
            tryCount = tryCount =+ 1
            if tryCount < 5:
                logEvent('BI File Write Error #'+str(tryCount), False)
            else:
                logEvent('BI File Write Failed', False)
Related