-2

I have the following python code which tries to copy a file stored in a variable file from a variable directory dir. I also attempting get those variables passed as shell variables, then I can copy using shell command as well.

Is any/both of these possible? Then please amend my code.

import os
import shutil
import subprocess


dir='somedir'
file='somefile'

# Now I want to get $dir as a shell variable and copy the file to
#   my present directory

os.system("echo $dir")
os.system("cp $dir/$file .")

# I want to copy dir/file to the present directory

shutil.copy(dir/file,file) # Following shutil.copy(src,dest) format
shutil.copyfile(dir/file,file)

The

hbaromega
  • 2,317
  • 2
  • 24
  • 32
  • Possible duplicate of [Python string formatting: % vs. .format](https://stackoverflow.com/questions/5082452/python-string-formatting-vs-format); is there any other dupe for string formatting? – Taku Mar 26 '18 at 10:19
  • Possible duplicate of [building full path filename in python,](https://stackoverflow.com/questions/7132861/building-full-path-filename-in-python) – Aran-Fey Mar 26 '18 at 10:19
  • Don't use `os.system` to copy files. Why use a platform-dependent solution of you can just use python instead? Anyway, the problem with your `shutil.copy(dir/file, file)` is that `dir/file` is invalid. You can't divide strings. Use `os.path.join` to combine them into a file path. – Aran-Fey Mar 26 '18 at 10:20
  • use string format `os.system("echo ${}".format(dir)) os.system("cp ${}/${} .".format(dir, file))` more info https://docs.python.org/2/library/string.html#format-string-syntax – Mauricio Cortazar Mar 26 '18 at 10:23

1 Answers1

1

You can do it simply in Python itself like below:-

import os
import shutil

dir = 'somedir'
file = 'somefile'
file_to_copy = dir + "/" + file
current_location = os.getcwd()
shutil.copy(file_to_copy, current_location)

Now your file somefile in location somedir will be copied to your current directory location.

Abhijit Pritam Dutta
  • 5,521
  • 2
  • 11
  • 17