python移动文件到另一个文件夹

python移动文件到另一个文件夹

在Python中,你可以使用`shutil`模块来移动文件到另一个文件夹。下面是一个简单的例子,展示了如何使用`shutil.move()`函数来移动文件:

```python

import shutil

源文件的路径

source_file = '/path/to/source/file.txt'

目标文件夹的路径

destination_folder = '/path/to/destination/folder'

使用shutil.move()函数移动文件

shutil.move(source_file, destination_folder)

```

如果你需要移动整个文件夹,可以使用`shutil.move()`函数,并指定要移动的文件夹和目标文件夹:

```python

import shutil

源文件夹的路径

source_folder = '/path/to/source/folder'

目标文件夹的路径

destination_folder = '/path/to/destination/folder'

使用shutil.move()函数移动整个文件夹

shutil.move(source_folder, destination_folder)

```

请注意,移动文件夹时,目标文件夹必须存在,否则会抛出一个异常。如果目标文件夹不存在,你可以先使用`os.makedirs()`函数创建它:

```python

import os

import shutil

源文件夹的路径

source_folder = '/path/to/source/folder'

目标文件夹的路径

destination_folder = '/path/to/destination/folder'

如果目标文件夹不存在,则创建它

if not os.path.exists(destination_folder):

os.makedirs(destination_folder)

使用shutil.move()函数移动整个文件夹

shutil.move(source_folder, destination_folder)

```

以上代码示例展示了如何使用Python将文件或文件夹从一个位置移动到另一个位置。

# 您可以还会对下面的文章感兴趣: