In python 2.7.2, i need to make a copy of a file in Linux.
newfile = "namePart1" + dictionary[key] + "namePart2"
os.system("cp cfn5e10_1.lp newfile")
But, the newfile cannot be replaced by its correct string.
the posts in the forum cannot help.
Any help is really appreciated.
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)
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)
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.
来源:https://stackoverflow.com/questions/11584502/run-cp-command-to-make-a-copy-of-a-file-or-change-a-file-name-in-python