写一个批量移动文件到另一个硬盘文件夹的python脚本
时间: 2023-09-07 19:05:23 浏览: 83
### 回答1:
这是一个简单的python脚本,用于批量移动文件到另一个硬盘文件夹:import ossourceFolder = r"C:\path\to\source"
destFolder = r"C:\path\to\destination"for root, dirs, files in os.walk(sourceFolder):
for file in files:
src_file = os.path.join(root, file)
dst_file = os.path.join(destFolder, file)
if not os.path.exists(dst_file):
os.rename(src_file, dst_file)
### 回答2:
下面是一个用Python编写的批量移动文件到另一个硬盘文件夹的脚本:
```python
import os
import shutil
def move_files(source_dir, destination_dir):
# 遍历源文件夹中的所有文件
for filename in os.listdir(source_dir):
# 构建源文件的完整路径
source_file = os.path.join(source_dir, filename)
# 如果是文件而不是文件夹
if os.path.isfile(source_file):
# 构建目标文件的完整路径
destination_file = os.path.join(destination_dir, filename)
# 使用shutil库的move()方法移动文件
shutil.move(source_file, destination_file)
# 源文件夹路径
source_directory = "C:/source"
# 目标文件夹路径
destination_directory = "D:/destination"
# 调用move_files函数,将源文件夹中的文件移动到目标文件夹
move_files(source_directory, destination_directory)
```
以上脚本首先导入了`os`和`shutil`库,`os`库用于操作文件和文件夹,`shutil`库用于移动文件。然后定义了一个`move_files`函数,该函数接收源文件夹路径和目标文件夹路径作为参数。在函数中,通过遍历源文件夹中的所有文件,构建源文件的完整路径,并判断是否为文件而不是文件夹。如果是文件,就构建目标文件的完整路径,并使用`shutil.move()`方法将文件移动到目标文件夹中。
最后,定义了源文件夹路径和目标文件夹路径,并调用`move_files`函数来执行文件移动操作。
### 回答3:
下面是一个批量移动文件到另一个硬盘文件夹的Python脚本示例:
```python
import os
import shutil
def move_files(source_directory, destination_directory):
# 遍历源文件夹中的文件
for file_name in os.listdir(source_directory):
# 构建源文件的完整路径
source_file = os.path.join(source_directory, file_name)
# 如果是文件而不是文件夹
if os.path.isfile(source_file):
# 构建目标文件夹中的文件路径
destination_file = os.path.join(destination_directory, file_name)
# 使用shutil模块的move函数移动文件
shutil.move(source_file, destination_file)
print(f"已成功移动文件 {file_name} 到目标文件夹.")
# 源文件夹路径
source_directory = 'C:/源文件夹的路径'
# 目标文件夹路径
destination_directory = 'D:/目标文件夹的路径'
# 执行移动文件操作
move_files(source_directory, destination_directory)
```
上述脚本中,我们首先导入了Python的os和shutil模块。然后定义了一个名为`move_files`的函数,该函数接收源文件夹路径和目标文件夹路径作为参数。
在`move_files`函数中,我们使用`os.listdir`遍历源文件夹中的所有文件名。然后构建每个文件的完整路径。接下来,我们检查文件是否为文件而不是文件夹,以确保只移动文件。
在移动文件之前,我们构建目标文件夹中文件的完整路径。最后,我们使用`shutil.move`函数将源文件移动到目标文件夹中,并打印成功移动的文件名。
最后,我们定义了源文件夹路径和目标文件夹路径,并调用`move_files`函数来执行文件移动操作。
请注意,您需要将源文件夹路径和目标文件夹路径替换为实际的文件夹路径。另外,确保您具有对目标文件夹的写入权限。