Create a new directory based on the entered path and name and copy the file there, the path and name of which is specified by the user from the console (terminal)

Hi. Could you help me. How can I enter the path where a new directory will be created and copy the specified file there from another file folder
package main

All I did was create a directory in the same location as the program.

import (

func main() {
	wd, err := os.Getwd()
	if err != nil {
		fmt.Println("Error:", err)

	fmt.Println("Working Directory:", wd)
	fmt.Println("Application:", filepath.Join(wd, os.Args[0]))
	d := filepath.Join(wd, "test")
	if err := os.Mkdir(d, 0755); err != nil {
		fmt.Println("Error:", err)
	fmt.Println("Created", d)
	if err := os.Chdir(d); err != nil {
		fmt.Println("Error:", err)
	fmt.Println("New Working Directory:", d)

Hi, Vlad,

Do you mean that you want to interactively prompt the user for the path, or that you want to specify the path when the program starts (like a command line argument or switch)? If the former, then you can use a member of the “Print family” of functions from the fmt package (e.g. Println, Printf, Fprintf, etc.) to print the question for the path and a member of the “Scan family” of functions to read the input from the user (e.g. Scanln). If the latter, then you can look into the flag package which gives you functions like flag.String and flag.StringVar will let you define flags that can be used from the command line.

I’m not aware of any built-in simple way to copy files in Go like, for example, the Python shutil package, but I did find a port of that package here. I have never used it and cannot provide an opinion. Instead, you have to:

  1. Use something like os.Open to open the source file for reading, Don’t forget to close it when you’re done!,
  2. Use something like os.Create to create/overwrite the destination file for writing, Don’t forget to close it when you’re done!,
  3. Use something like io.Copy to copy the data from the source to the destination. Note the order of the parameters!.

I say “something like …” each time because your situation may require more control. If you need the file to be opened with certain flags, you might instead need os.OpenFile or something else to open the file. If you need to append to existing files instead of overwriting, then you need to use os.OpenFile with specific flags, etc.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.