复制特定文件量

问题描述 投票:0回答:1

当使用 google colab 和 python 语言时。如何将特定数量的数据(例如 100 个文件(来自 900 个文件))从下载的目录复制到另一个目录?由于我使用此命令,它会复制 din 目录中的所有文件

!cp /content/dataset/train/rottenapples/*.png /content/fresh_rotten/rotten_pic

是否使用特定范围的循环?

python google-colaboratory
1个回答
0
投票
import os
import shutil

# Source directory containing the 900 files
source_dir = '/content/dataset/train/rottenapples/'

# Destination directory where you want to copy the files
destination_dir = '/content/fresh_rotten/rotten_pic/'

# List all files in the source directory
files = os.listdir(source_dir)

# Copy the first 100 files from the source directory to the destination directory
for file_name in files[:100]:
    source_file = os.path.join(source_dir, file_name)
    shutil.copy(source_file, destination_dir)

您可以在 Google Colab 的代码单元中运行此代码来复制指定数量的文件。根据您的实际目录结构调整路径(source_dir和destination_dir)。

© www.soinside.com 2019 - 2024. All rights reserved.