Python 代码:将目录中的图片文件移动到另一个目录
以下是一个示例的 Python 代码,可以将一个目录中的所有图片文件移动到另一个目录中:\n\npython\nimport os\nimport shutil\n\ndef move_images(source_dir, destination_dir):\n # 获取源目录中的所有文件和文件夹\n files = os.listdir(source_dir)\n \n # 遍历源目录中的每个文件\n for file in files:\n # 构建文件的完整路径\n file_path = os.path.join(source_dir, file)\n \n # 检查当前路径是否为文件,并且是否为图片文件(可根据具体需求进行更改)\n if os.path.isfile(file_path) and file.lower().endswith(('.png', '.jpg', '.jpeg', '.gif')):\n # 构建目标目录中的文件路径\n destination_path = os.path.join(destination_dir, file)\n \n # 将文件移动到目标目录中\n shutil.move(file_path, destination_path)\n \n print(f"Moved {file} to {destination_dir}")\n \nsource_directory = "path/to/source/directory"\ndestination_directory = "path/to/destination/directory"\n\nmove_images(source_directory, destination_directory)\n\n\n请将代码中的source_directory和destination_directory替换为实际的目录路径。此代码将遍历源目录中的每个文件,如果是图片文件(.png、.jpg、.jpeg、.gif),则将其移动到目标目录中,并在控制台打印出移动的文件名和目标目录的路径。
原文地址: https://www.cveoy.top/t/topic/p2NG 著作权归作者所有。请勿转载和采集!