第三十四节 文件移动Move a File
- 前言
- 实践
前言
当我们需要将一个文件/文件夹移动到另一个指定路径时,就需要用到shutil.move()
函数,该函数需要指定两个参数shutil.move(src, dst)
,第一个表示源路径名称,第二个表示目标路径名称。这里的移动操作对应键盘的”剪切,粘贴”。
实践
我们还以lyric.txt
为例讲解文件移动操作,我们的目标是将该文件移动到G盘:
import os
import shutil
source = r"C:\Users\shen_student\Desktop\lyric.txt"
destination = r"G:\lyric.txt"
try:
if os.path.exists(destination):
print("There is already a file there")
else:
shutil.move(source, destination)
print(source + " was moved")
except FileNotFoundError:
print(source + " was not found")
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
我们来分析上述代码,首先分别指定源文件路径source
以及目标路径名称destination
。首先我们需要判断源路径指定的文件是否存在,如果不存在则抛出异常。如果存在,我们进一步判断指定路径中的文件是否已经存在,如果已经存在那就不需要做文件移动操作。如果不存在我们再把源路径文件移动到目标路径下。
shutil.move()
函数除了移动文件之外还可以移动文件夹,只需要指定源路径文件夹以及目标路径文件夹即可:
import os
import shutil
source = r"C:\Users\shen_student\Desktop\temp"
destination = r"G:\temp"
try:
if os.path.exists(destination):
print("There is already a file there")
else:
shutil.move(source, destination)
print(source + " was moved")
except FileNotFoundError:
print(source + " was not found")
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
例如我们想把源路径下的temp文件夹移动到G盘,那么用上述代码就可以。
以上便是文件移动的全部内容,感谢大家的收藏、点赞、评论。我们下一节将介绍文件删除(Delete a File),敬请期待~