go-在指定的路径中创建一个新文件

Trying to make a portable way to create a file in a specified directory within my $GOPATH.

  var FileName string = "Foci.db" 
  var Driver string = "sqlite3" 

  func Connect(fileName string) (*sql.DB, error) { 
      filePath, _ := filepath.Abs("../data/" + FileName) 
      // Create db if it doesn't exist 
      os.Open(filePath)
      // Open existing db 
      return sql.Open(Driver, filePath) 
  } 

However, this doesn't seem to create the file in the data directory as I hoped. Am I doing something wrong?

Open() won't create the file. Try Create() instead.

You were probably looking to use os.OpenFile

As the other poster mentioned you can use Create() and then Open() after it's created.

If you need high specificity, os.OpenFile can be useful as it allows you to set the path, flags (read only, write only etc.) and permissions all in one go.

Eg.

f, err := os.OpenFile(filepath, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
    //handle error
}

defer f.Close()