0

Hi I'm new to python programming.

I want to copy a file from source to destination. I'm using shutil.copy2(src,dst). But in src and dst path , I want to use variable.

For example (variable name): pkg_name = XYZ_1000 so src path will be : /home/data/$pkg_name/file.zip

In shell we can use $pkg_name to access variable, so is there any similar way in python?

Main concern is , if I want to use a variable(s) in copy command , how can I achieve that in python ? Thanks in advance.

deepu
  • 147
  • 2
  • 12

1 Answers1

3
pkg_name = XYZ_1000

using format()

src_path = "/home/data/{pkg_name}/file.zip".format(pkg_name=pkg_name)

OR

src_path = "/home/data/%s/file.zip" % pkg_name

OR

src_path = "/home/data/" + pkg_name + "/file.zip"

OR

src_path = string.Template("/home/data/$pkg_name/file.zip").substitute(locals())
# Or maybe globals() instead of locals(), depending on where pkg_name is defined.
chepner
  • 497,756
  • 71
  • 530
  • 681
alexisdevarennes
  • 5,437
  • 4
  • 24
  • 38
  • I added an example of a `string.Template` just for completeness. I wouldn't actually recommend using it, and there are a few ways of passing the value of `pkg_name` if you want to [read about it in the documentation](https://docs.python.org/2/library/string.html#template-strings). – chepner Jun 04 '15 at 16:06
  • @chepner, Thank you so much – deepu Jun 05 '15 at 00:51