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

心不动则不痛 提交于 2019-12-08 02:14:34

问题


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.


回答1:


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)



回答2:


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)



回答3:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!