我要复制到另一个文件夹(destination_folder)的一个文件夹(图像)中有一堆jpg。复制它们时,我希望将jpg文件重命名如下:filename1_red.jpg,filename2_red.jpg(即在末尾加上_red后缀)
到目前为止,我有以下内容:
import os
images = os.listdir('C:/Users/Admin-dsc/Documents/.../buses and motorcycles')
destination_folder = 'C:/Users/Admin-dsc/Documents/.../Buses'
for img in images:
filename = os.path.basename(img)
copyfile(img, os.path.join(destination_folder, filename))
问题1:我收到一个我不明白的错误-我该如何解决:
FileNotFoundError: [Errno 2] No such file or directory: 'RWG074059_2_o.jpg'
问题2:我不确定如何获得后缀。
有人可以帮忙吗?
答案 0 :(得分:1)
os.listdir
仅返回指定文件夹中文件的文件名,而不返回文件的完整路径。因此,您需要使用img
连接源文件夹路径:
import os
from shutil import copyfile
source_folder = 'C:/Users/Admin-dsc/Documents/.../buses and motorcycles'
destination_folder = 'C:/Users/Admin-dsc/Documents/.../Buses'
images = os.listdir(source_folder)
for img in images:
filename, ext = os.path.splitext(img)
filename = filename + '_red' + ext
copyfile(os.path.join(source_folder, img), os.path.join(destination_folder, filename))
答案 1 :(得分:1)
如何调试此错误:
import os
directory = 'C:/Users/Admin-dsc/Documents/.../buses and motorcycles'
images = os.listdir(directory)
for img in images:
print(img)
filename = os.path.basename(img)
print(filename)
输出:
main.py
main.py
您看到的内容:
您看到listdir()
仅返回文件名。您需要再次在源文件夹之前。
如何解决:
import os
directory = './'
destination_folder = 'C:/Users/Admin-dsc/Documents/.../Buses'
images = os.listdir(directory)
for img in images:
print(img)
filename = os.path.basename(img)
print(filename)
# prepend path again
source = os.path.join(directory,img)
target = os.path.join(destination_folder,img)
print(source, "=>", target)
# copyfile(source, target)
输出:
./main.py => C:/Users/Admin-dsc/Documents/.../Buses/main.py
答案 2 :(得分:0)
img
仅包含图像名称,而不包含完整的路径信息。
当您指定源图像时,请构建一个中止路径:
import os
source_folder = 'C:/Users/Admin-dsc/Documents/.../buses and motorcycles'
images = os.listdir(source_folder)
destination_folder = 'C:/Users/Admin-dsc/Documents/.../Buses'
for img in images:
filename = os.path.basename(img)
copyfile(os.path.join(source_folder, img), os.path.join(destination_folder, filename))