运行cp命令以在Python中复制文件或更改文件名 [英] run cp command to make a copy of a file or change a file name in Python
问题描述
在python 2.7.2中,我需要在Linux中制作文件的副本.
In python 2.7.2, i need to make a copy of a file in Linux.
newfile ="namePart1" +字典[key] +"namePart2"
newfile = "namePart1" + dictionary[key] + "namePart2"
os.system("cp cfn5e10_1.lp newfile")
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.
推荐答案
使用 shutil.copyfile
复制文件而不是 os.sytem
,它不需要创建新进程,它将自动处理文件名中带有不寻常字符的文件名他们,例如空格- os.system
只是将命令传递给shell,shell可能会破坏其中包含空格的文件名以及其他可能的问题.
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.
例如:
newfile = "namePart1" + dictionary[key] + "namePart2"
shutil.copyfile("cfn5e10_1.lp", newfile)
这篇关于运行cp命令以在Python中复制文件或更改文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!