Search code examples
robotframework

Robot Framework - run keyword if file exists


How can you run keywords in the robot framework if the file exists in the filesystem? For example:

Run Keyword If    ${filename} exists    Delete File

Solution

  • OperatingSystem library could be used for this, even though there's not exactly any keyword for what you need. But you can get creative and perhaps use Get File, Get File Size, List Files In Directory, Run And Return Rc or even something else. There are also keywords like File Should Exist, File Should Not Exist, Should Exist. Perhaps you can change your code so you can use these.

    Or you create your own simple library:

    Libraries/file.py

    import os
    
    def file_exists(file):
        return os.path.isfile(file)
    

    import it and use it like you mentioned in your question:

    Tests/test.robot

    *** Settings ***
    Library    ../Libraries/file.py    
    
    *** Test Cases ***
    Test File Exists
        ${fileExists}=    File Exists    test.robot
        Run Keyword If    ${fileExists} is True    Log To Console    Exists!