如何使用Python重命名文件

在 shell 命名中,我们很通过mv命令,可以很简单的移动一个文件到另外一个位置,或者重命名一个文件为另外一个名字。

在 unix 系统中,mv 命令可以用来移动文件,同时,也可以用来重命名一个文件。

使用Python的osshutil模块也可以重命名文件

os.rename()shutil.move()方法都可以实现类似与 shell 中的mv命令相似的功能。

1
2
3
4
5
6
7
8
9
10
11
def rename(*args, **kwargs): # real signature unknown
"""
Rename a file or directory.

If either src_dir_fd or dst_dir_fd is not None, it should be a file
descriptor open to a directory, and the respective path string (src or dst)
should be relative; the path will then be relative to that directory.
src_dir_fd and dst_dir_fd, may not be implemented on your platform.
If they are unavailable, using them will raise a NotImplementedError.
"""
pass
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
def move(src, dst, copy_function=copy2):
"""Recursively move a file or directory to another location. This is
similar to the Unix "mv" command. Return the file or directory's
destination.

If the destination is a directory or a symlink to a directory, the source
is moved inside the directory. The destination path must not already
exist.

If the destination already exists but is not a directory, it may be
overwritten depending on os.rename() semantics.

If the destination is on our current filesystem, then rename() is used.
Otherwise, src is copied to the destination and then removed. Symlinks are
recreated under the new name if os.rename() fails because of cross
filesystem renames.

The optional `copy_function` argument is a callable that will be used
to copy the source or it will be delegated to `copytree`.
By default, copy2() is used, but any function that supports the same
signature (like copy()) can be used.

A lot more could be done here... A look at a mv.c shows a lot of
the issues this implementation glosses over.

"""

其中 shutil.move() 更加接近 Unix 的mv命令。os.rename()不支持移动一个文件到另外一个磁盘上,而 shutil.move() 可以支持。

在操作系统中,移动文件和重命名文件是一样的,只需要在文件系统中修改文件表信息,并不需要进行物理的移动。区别比较大的是,在 windows 系统上的多个分区之间的移动是需要进行物理移动的。

拷贝是需要进行物理拷贝的,所以很多时候你会发现,移动一个文件比复制一个文件要快一些。

知识就是财富
如果您觉得文章对您有帮助, 欢迎请我喝杯水!