首页 > 解决方案 > 使用 Python 代码将 100 个文件中的前 5 个文件从一个目录移动到另一个目录

问题描述

是否可以使用 python 代码将前 5 个文件从一个目录移动到另一个目录?我必须在数据砖笔记本上运行代码。

场景是:我必须选择目录中存在的前 5 个文件(文件总数为 100)并将这 5 个文件移动到另一个目录,这个过程将重复,直到所有文件移动到另一个文件夹。

标签: pythonazure-databricks

解决方案


r'' - 原始字符串文字(忽略字符串中的反斜杠)

import os
import shutil

source = r'C:\Python38-32'                # files location
destination = r'C:\New Folder'            # where to move to 
folder = os.listdir(source)               # returns a list with all the files in source

while folder:                             # True if there are any files, False if empty list
   for i in range(5):                     # 5 files at a time 
      file = folder[0]                    # select the first file's name
      curr_file = source + '\\' + file    # creates a string - full path to the file
      shutil.move(curr_file, destination) # move the files
      folder.pop(0)                       # Remove the moved file from the list

为我工作,将文件从一个目录 ( source) 移动到另一个 ( destination)


推荐阅读