run cp command to make a copy of a file or change a file name in Python

Question:

I want to use Python to run the cp command on Linux, thus copying a file. I have this code:

newfile = "namePart1" + dictionary[key] + "namePart2"

os.system("cp cfn5e10_1.lp newfile")

How can I make it so that the text newfile on the second line is replaced with the newfile variable that I calculated on the previous line?

Asked By: user1002288

||

Answers:

Use shutil.copyfile to copy a file instead of os.sytem, it doesn’t need to create a new process and it will automatically handle filenames with unusual characters in them, e.g. spaces — os.system just passes the command to the shell, and the shell might break up filenames that have spaces in them, among other possible issues.

For example:

newfile = "namePart1" + dictionary[key] + "namePart2"
shutil.copyfile("cfn5e10_1.lp", newfile)
Answered By: Adam Rosenfield

This will not replace newfile with your variable.

os.system("cp cfn5e10_1.lp newfile")

You need to concatenate the variable to the end of the string like so:

os.system("cp cfn5e10_1.lp " + newfile)
Answered By: Daniel Li

If you want to call cp from Python, use the subprocess module:

subprocess.call(["cp", "cfn5e10_1.lp", "newfile"])

But it’s better to use a function from the shutil module instead.

Answered By: MRAB
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.