如何使用Python将所有文件从一个目录移动到另一个目录?
在本文中,我们将看到如何使用Python将所有文件从一个目录移动到另一个目录。在我们日常的计算机使用中,我们通常将文件从一个文件夹复制或移动到另一个文件夹,现在让我们使用Python来做同样的事情。
这可以通过两种方式完成:
- 使用 os 模块。
- 使用shutil模块。
源和目标文件夹
![](https://mangodoc.oss-cn-beijing.aliyuncs.com/geek8geeks/How_to_move_all_files_from_one_directory_to_another_using_Python_?_0.jpg)
源文件夹和目标文件夹
![](https://mangodoc.oss-cn-beijing.aliyuncs.com/geek8geeks/How_to_move_all_files_from_one_directory_to_another_using_Python_?_1.jpg)
源文件夹
![](https://mangodoc.oss-cn-beijing.aliyuncs.com/geek8geeks/How_to_move_all_files_from_one_directory_to_another_using_Python_?_2.jpg)
目标文件夹 – 之前
方法 1:通过使用 os 模块中的 rename() 方法
rename() 方法接受两个参数,第一个是源路径,第二个是目标路径,重命名函数会将源路径中的文件移动到提供的目标。
首先导入os模块,存储源目录路径和目的目录路径,使用os模块中的listdir()方法列出源目录下的所有文件。现在使用 rename() 方法将列表中的所有文件一一移动。
代码:
Python3
import os
source = 'C:/Users/sai mohan pulamolu/Desktop/deleted/source/'
destination = 'C:/Users/sai mohan pulamolu/Desktop/deleted/destination/'
allfiles = os.listdir(source)
for f in allfiles:
os.rename(source + f, destination + f)
Python3
import os
import shutil
source = 'C:/Users/sai mohan pulamolu/Desktop/deleted/source/'
destination = 'C:/Users/sai mohan pulamolu/Desktop/deleted/destination/'
allfiles = os.listdir(source)
for f in allfiles:
shutil.move(source + f, destination + f)
方法二:使用shutil模块中的move()方法
Shutil.move() 方法接受两个参数,第一个是源路径,第二个是目标路径,移动函数会将源路径上的文件移动到提供的目标。
首先导入shutil模块,存放源目录的路径和目的目录的路径。使用 os 模块中的 listdir() 方法列出源目录中的所有文件。现在使用shutil.move() 方法将列表中的所有文件一一移动。
蟒蛇3
import os
import shutil
source = 'C:/Users/sai mohan pulamolu/Desktop/deleted/source/'
destination = 'C:/Users/sai mohan pulamolu/Desktop/deleted/destination/'
allfiles = os.listdir(source)
for f in allfiles:
shutil.move(source + f, destination + f)
两个输出是相同的:
![](https://mangodoc.oss-cn-beijing.aliyuncs.com/geek8geeks/How_to_move_all_files_from_one_directory_to_another_using_Python_?_3.jpg)
目标文件夹 – 之后