如何将扩展名.png图形从一个文件夹移动或复制到另一个文件夹?



我在文件夹Dist中保存了一个带有.png扩展名的图形。现在在 for 循环中,我想实现一个条件,即如果 i<3 将某个图形从一个文件夹移动或复制到另一个文件夹。我怎样才能在 python 中做到这一点?

以下是如何将文件复制到另一个文件夹的两种方法:

例如,如果我们有这个树目录:

.
├── destination  # destination directory
├── moving.py    # script that copies files
└── test.png     # file to be copied

moving.py:

import os
import shutil

# Method 1
def copy_file(filename: str, destination: str):
"""Copy file to destination using shutil package
:param: filename is the file name path
:param: destination is the destination path
"""
shutil.copy(filename, destination)

# Method 2
def copy_file2(filename: str, destination: str):
"""Copy file to destination"""
data = b''
# Read the file in binary mode
with open(filename, 'rb') as f:
data = f.read()
# Write the file in binary mode
with open(os.path.join(destination, filename), 'wb') as f:
f.write(data)

# Example
filename = 'test.png'
destination = 'destination'
copy_file(filename, destination)
# copy_file2(filename, destination)

这两种方法都会将文件复制到新的目标路径,并保留复制文件的原始名称。

奖励:有关shutil.copy()功能的更多信息,我建议您阅读官方文档

相关内容

最新更新