Python: Check if file was saved

I want to be able to check if the working .blend file has been saved when a user presses a button. If it has not been, Blender should give an error.

I just want the user to save before running my add-on.

• @RayMairlot I don't quite understand why this isn't specifically about Blender, as he is asking how to determine (from within Blender, using Blender's UI) if a Blender file has been saved. – PGmath Jul 27 '16 at 16:09
• @PGmath I don't think it's relevant that it's done within Blender and I didn't see the button press as a core part of the question (there are other questions already on this). As shown by the answer below, the answer is a purely python (not bpy) solution. – Ray Mairlot Jul 27 '16 at 16:14
• @PGmath I guess I may be misunderstanding the question as it's unclear if the 'file' they're referencing is a blender file and if they mean has it been saved since changes have been made or if the file isn't saved at all. Confirmation from OP would be helpful. – Ray Mairlot Jul 27 '16 at 16:19
• @RayMairlot The former was my impression. So OP please add some further clarification. – PGmath Jul 27 '16 at 16:20

If 'the file' you are referencing is a blender file and you want to know if it has been saved then there are two properties you can check.

If a blender file hasn't been saved at all you can check it's is_saved property as this will be False if it hasn't been saved:

if bpy.data.is_saved:
#File has been saved. Do something.


(A previous version of this answer instead checked if the filepath property was blank instead - the above is a correction thanks to poor's comment).

For files that have been saved you can check the is_dirty property, which will be True when changes have been made since the last save:

if bpy.data.is_dirty:
#Changes have been made since the last save. Do something.


To get a button to execute code have a look at Simple way to add button to UI.

For error messages look at Proper way to show users error info in the UI for addons.

• This is just what I needed. I already know how to add a button. – John Roper Jul 28 '16 at 12:58
• Nitpicking: Using is_saved flag is probably the better option to check if the file is saved - Has the current session been saved to disk as a .blend file If you really like to go with filepath the comparison operator is not necessary here. You can write if not bpy.data.filepath: to check an empty string, that's easier to understand and more pythonic: stackoverflow.com/a/9573259/3091066 – p2or Jul 29 '16 at 16:00
• @poor Thanks, don't know how I missed that option but I'll add it in. Also didn't know about the empty string, that's a great tip. – Ray Mairlot Jul 29 '16 at 16:03

Just to make Ray's answer more specific with my question:

The code should be

if bpy.data.is_dirty:

from os.path import isfile