KidMcC
KidMcC

Reputation: 486

Pausing script before error for open csv file

I am writing a python script that includes a lot of data manipulation using PANDAS and ultimately writing to CSVs.

When I accidentally leave a CSV file open in Microsoft Excel and then run my script which is altering/exporting to that CSV, I get the error warning me it is open and advising to close it.

Is there any way I can include something that will warn me that the CSV I am about to export/write to is open and pause the script before it errors out as a result? Maybe include a raw input that will resume the script when I enter "csv closed" or something?

Thanks.

Upvotes: 2

Views: 78

Answers (1)

behzad.nouri
behzad.nouri

Reputation: 77971

You can wrap the line of code in a while loop, and break out of the loop on successful execution or when the user does not want to retry:

while True:
    try:
        # try something which may fail
        # ...

        break  # successful run, break out of loop
    except Exception as err:
        print(err)
        ans = input('retry (y/n)? ')
        if ans.lower() not in ['yes', 'y']:
            raise

Upvotes: 1

Related Questions