Write a file and create its ancestor directories if needed