Skip to content
Advertisement

flask/pythonanywhere – FileNotFoundError: [Errno 2] when trying to create a new folder

I am having problems when deploying a Flask app into pythonanywhere.

I do have a signup form and when the user sings up, I want to create a folder with the username and a .josn file inside the folder to store other data that the user will input later on.

It works perfectly in my local server, but when uploading the project into pyhtonanywhere I get the following error:

FileNotFoundError: [Errno 2] No such file or directory: ‘/home/XXX/app/static/JsonData/foldername’

It looks like having problems to find the path but I don’t know how to solve it. Here my code:

        ## ----------- CREATE A FOLDER WITH USERNAME (TO STORE JSON FILES) --------- ##
        ## creates a folder in JsonData folder to store the project data files ##
        ## the folder name is = username used to signup ##
        cwd=os.getcwd()
        path=os.path.join(cwd, new_user.username)
        os.mkdir(path)

        ## ----------- CREATES FIRST JSON FILE TO STORE PROJECT DATA --------- ##
        # creates a first json file called username_BaseScenario stored in the previous folder
        jsonName=formSignup.username.data + '_BaseScenario.json'
        filePath=os.path.join(path, jsonName)

       ## ---- CREATES A NEW JSON FILE TO STORE PROJECT DATA ------ ##
        #create a dictionary that will be transformed into a json file
        newProject={
                   bunch of lines code for the dictionary
        }

        #converts the dict to json and store it in the fileName path
        with open(filePath, 'w') as outfile:
            json.dump(newProject, outfile)

I am usign the getcwd() which I thought it was an absolute path and it should work, but I don’t know. Any help will be much appreciated. I readed some answers about similar problems but I was not able to solve it, I tried harcoding the path, but with the same result. so it mustbe something else

Advertisement

Answer

Current working directory might not be what you expect to be. It’s better to use os.path.dirname(__file__) to get the path of the file that is executed as the point of reference.

On PythonAnywhere though, you can manipulate your project’s CWD on the Web page (Working directory setting).

Another thing is, that the error you showed implies that '/home/XXX/app/static/JsonData/ doesn’t exist, so that doesn’t match the code you showed (the error comes from a different bit of code or you changed the code meanwhile, perhaps?).

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement