Write file to specific folder in project

Viewed 69

I currently have a python file that outputs data in a .json and saves it to a folder in my project which is located on my desktop:

let dirPath = "/Users/Admin/Desktop/DataExchangeExercise/DataExchangeExercise/"

This folder is where my Xcode project is located. However, I would like my program to just write to the project folder by itself without me directing to it manually so if I move my project it still works. I am calling my python file from swift like this:

func runPythonCode(){
  let sys = Python.import("sys")
  sys.path.append(dirPath)
  let example = Python.import("Users")
  example.writeToJSONFile()
}

I have tried changing dirPath to: let dirPath = Bundle.main.bundlePath but it is not putting the file where I want it in my XCode project, because then my read function does not work with it anymore:

func readLocalFile(forName name: String) -> Data? {
    do {
        if let bundlePath = Bundle.main.path(forResource: fileName, ofType: "json"),
            let jsonData = try String(contentsOfFile: bundlePath).data(using: .utf8) {
            return jsonData
        }
    } catch {
        print("error")
    }
    return nil
}

Any ideas on how to get the file where I want it to go?

0 Answers
Related