Search code examples
pythonshellvariablescopylanguage-comparisons

Is there any way to access variable like $var (similar to shell scripting) in python?


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.


Solution

  • 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.