run cp command to make a copy of a file or change a file name in Python
bash, cp, linux, python, shell
Solution
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)
Problem
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?