Search code examples
pythonjsonlistdirectorywritefile

How to to check if a folder doesn't exist to create a file inside of it?


I am trying to check if folder exist if not the system create it and a JSON file will be written inside this folder.

The problem is that the system create an empty folder and displays this error:

None

 the selected file is not readble because :  [WinError 183] Cannot
 create a file when that file already exists: './search_result'
 'NoneType' object is not iterable

None is the result of: print(searchResultFoder).

The code is:

if not(os.path.exists("./search_result")):                                      
                    today = time.strftime("%Y%m%d__%H-%M")
                    jsonFileName = "{}_searchResult.json".format(today)
                    fpJ = os.path.join(os.mkdir("./search_result"),jsonFileName)
                    print(fpJ)
with open(fpJ,"a") as jsf:
                    jsf.write(jsondata)
                    print("finish writing")

Solution

  • Issues with code :

    • Case Directory Doesn't exist : os.mkdir("./search_result") in fpJ = os.path.join(os.mkdir("./search_result"),jsonFileName) returns nothing you have assumed it will return you the path of the created folder. which is incorrect.

    • Case Directory exists : In case when condition if not(os.path.exists("./search_result")):
      is false json file name will be undefined and throw and exception

    . Full working example of code which is doing the following. 1) check if folder exist if not create it 2) write the JSON FILE inside this created folder.

    import json
    import os
    import time
    
    jsondata = json.dumps({"somedata":"Something"})
    folderToCreate = "search_result"
    today = time.strftime("%Y%m%d__%H-%M")
    jsonFileName = "{}_searchResult.json".format(today)
    
    if not(os.path.exists(os.getcwd()+os.sep+folderToCreate)):
                        os.mkdir("./search_result")
    
    fpJ = os.path.join(os.getcwd()+os.sep+folderToCreate,jsonFileName)
    print(fpJ)
    
    with open(fpJ,"a") as jsf:
                        jsf.write(jsondata)
                        print("finish writing")
    

    Hope this helps