os.rename()
, shutil.move()
, or os.replace()
(os.rename()
, shutil.move()
或os.replace()
)
All employ the same syntax: (全部采用相同的语法:)
import os
import shutil
os.rename("path/to/current/file.foo", "path/to/new/destination/for/file.foo")
shutil.move("path/to/current/file.foo", "path/to/new/destination/for/file.foo")
os.replace("path/to/current/file.foo", "path/to/new/destination/for/file.foo")
Note that you must include the file name ( file.foo
) in both the source and destination arguments. (请注意,您必须在源和目标参数中都包含文件名( file.foo
)。) If it is changed, the file will be renamed as well as moved. (如果更改,文件将被重命名和移动。) Note also that in the first two cases the directory in which the new file is being created must already exist. (还请注意,在前两种情况下,用于创建新文件的目录必须已经存在。) On Windows, a file with that name must not exist or an exception will be raised, but os.replace()
will silently replace a file even in that occurrence. (在Windows上,必须不存在具有该名称的文件,否则将引发异常,但是os.replace()
会静默替换该文件,即使在这种情况下也是如此。)
As has been noted in comments on other answers, shutil.move
simply calls os.rename
in most cases. (正如在其他答案的评论所指出, shutil.move
简单的调用os.rename
在大多数情况下。) However, if the destination is on a different disk than the source, it will instead copy and then delete the source file. (但是,如果目标与源位于不同的磁盘上,它将代替复制然后删除源文件。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…