bash 在 Python 中运行 cp 命令来制作文件的副本或更改文件名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11584502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 02:49:58  来源:igfitidea点击:

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

pythonlinuxbashshellcp

提问by user1002288

In python 2.7.2, i need to make a copy of a file in Linux.

在 python 2.7.2 中,我需要在 Linux 中制作一个文件的副本。

newfile = "namePart1" + dictionary[key] + "namePart2"

newfile = "namePart1" + 字典[key] + "namePart2"

os.system("cp cfn5e10_1.lp newfile")

os.system("cp cfn5e10_1.lp 新文件")

But, the newfile cannot be replaced by its correct string.

但是,新文件不能被其正确的字符串替换。

the posts in the forum cannot help.

论坛中的帖子无济于事。

Any help is really appreciated.

任何帮助都非常感谢。

回答by Adam Rosenfield

Use shutil.copyfileto 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.systemjust passes the command to the shell, and the shell might break up filenames that have spaces in them, among other possible issues.

使用shutil.copyfile复制文件,而不是os.sytem,它并不需要创建一个新的过程,它会自动处理与他们的特殊字符,如空格的文件名-os.system只是传递命令外壳,壳可能向上突破该文件名其中有空格,以及其他可能的问题。

For example:

例如:

newfile = "namePart1" + dictionary[key] + "namePart2"
shutil.copyfile("cfn5e10_1.lp", newfile)

回答by Daniel Li

This will not replace newfilewith your variable.

这不会替换newfile为您的变量。

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)

回答by MRAB

If you want to call cpfrom Python, use the subprocessmodule:

如果cp要从 Python调用,请使用subprocess模块:

subprocess.call(["cp", "cfn5e10_1.lp", "newfile"])

But it's better to use a function from the shutilmodule instead.

但最好使用shutil模块中的函数。