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

久未见 提交于 2019-12-06 12:45:26

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.

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