复制特定数量的文件

-2 投票
1 回答
41 浏览
提问于 2025-04-11 23:56

在使用 Google Colab 和 Python 语言时,怎样才能从下载的文件夹里复制特定数量的文件,比如从900个文件中只复制100个到另一个文件夹呢?因为我用的命令是把文件夹里的所有文件都复制过来了。

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

是不是需要用循环来指定一个范围呢?

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)。

撰写回答