我在某个位置有一个文件,我想将该文件复制到另一个位置但使用不同的名称。此操作将重复多次,并且在每种情况下要复制的文件的基本名称都是相同的(仅位置不同),因此这就是重命名的原因。
无论如何,本指南中解释了执行此操作的方法。
代码是
import shutil
import os
# Specify the source file, the destination for the copy, and the new name
source_file = 'path/to/your/source/file.txt'
destination_directory = 'path/to/your/destination/'
new_file_name = 'new_file.txt'
# Copy the file
shutil.copy2(source_file, destination_directory)
# Get the base name of the source file
base_name = os.path.basename(source_file)
# Construct the paths to the copied file and the new file name
copied_file = os.path.join(destination_directory, base_name)
new_file = os.path.join(destination_directory, new_file_name)
# Rename the file
os.rename(copied_file, new_file)
到目前为止一切顺利。 我的问题是,通过仅使用
os.rename
,我们就能够“移动”文件。相比之下,复制真的有这么复杂吗?不是有一些方法可以用一个命令来复制和重命名吗?
注意:在有人将此问题标记为“重复”之前,请注意我正在上面提供基本问题的解决方案。 我要问的——因此不是重复的——是,如果就编写有效的Python而言,这不是一个更简单的方法。
你太复杂了,你可以将新文件的整个路径传递给
shutil.copy
:
import shutil
source_file = 'path/to/your/source/file.txt'
destination_file = 'path/to/your/destination/new_file.txt'
shutil.copy(source_file, destination_file)