【问题标题】:Script to copy multiple files to multiple directories将多个文件复制到多个目录的脚本
【发布时间】:2019-08-19 20:25:15
【问题描述】:

我有一个包含许多文件的目录:

abc.txt
def.txt
ghi.txt
   etc.

我编写了一个脚本,它根据每个文件的名称(目录 abc、def、ghi 等)创建一个新目录。

现在我想将文件 abc.txt 复制到目录 abc,将文件 def.txt 复制到目录 def 等等。

我正在尝试使用 shutil 执行此操作,但我的脚本不起作用。

import os, glob, shutil

myfiles = glob.glob("/users/source_directory/*.*")
for f in myfiles:
    file_name, file_extension = os.path.splitext(f)
    destination = (os.path.join('/users/destination_directory/',file_name))
    shutil.copy(f, (os.path.join(destination,file_name)))

这会生成一个源文件的副本,减去它在源目录中的文件扩展名。有关如何使其按预期工作的任何建议?

【问题讨论】:

  • 先制作目录

标签: python file-handling


【解决方案1】:

首先,您的 file_name 变量不仅包含文件名,还包含文件的整个绝对路径。这意味着目标变量的 os.path.join 命令将 /users/source_directory 覆盖 /users/destination_directory 路径。

其次,您必须创建新目录。

第三,我还为复制过程添加了文件扩展名。

以下代码正在完成您的工作。

import os, glob, shutil

myfiles = glob.glob("/users/source_directory/*.*")
for f in myfiles:
    file_path, file_extension = os.path.splitext(f)
    file_name = os.path.basename(file_path)
    destination = os.path.join('/users/destination_directory/',file_name)
    os.mkdir(destination)
    shutil.copy(f, (os.path.join(destination,file_name+file_extension)))

【讨论】:

  • 谢谢,现在说得通了。您的脚本完全符合我的预期。
猜你喜欢
  • 2013-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-15
  • 2015-08-21
  • 1970-01-01
  • 1970-01-01
  • 2020-03-22
相关资源
最近更新 更多