【问题标题】:How to rename a file while copying into another directory in python?复制到python中的另一个目录时如何重命名文件?
【发布时间】:2020-12-28 03:41:35
【问题描述】:

我想将文件从一个目录复制到另一个目录,同时在 python 中重命名该文件。 “文件”需要复制为“新文件”而不重命名源目录中的文件。我试过这样的东西;

     import shutil,os
     src_path="path of source directory"
     dst="path of destination directory"
     for file in os.listdir(src):
         file_path=os.path.join(src_path,file)
          shutil.copy(file_path,dst/"new"+'-'+file)

但是这不起作用。我知道通过使用 os.rename() 模块,它可以在复制后重命名。但是,我有名称相似的文件,它们将替换已经复制的文件,以避免我需要将每个文件重命名为“新文件”以及复制自身。

感谢任何帮助。提前致谢

【问题讨论】:

  • 你正在尝试分割字符串 -- dst/"new"
  • 而且你显然知道如何使用os.path.join,因为你在上一行使用了它。
  • @Ben 我已经发布了一个对原始代码进行了最小错误修复的答案,但是如果你也可以使用 pathlib 获得答案会很好 - 也许你可以发布一个?
  • 您使用它来确定新名称,包括路径。如果你不明白怎么做,那么你看看你自己的代码的前一行,你做了同样的事情。

标签: python rename shutil copying


【解决方案1】:

您使用dst/"new" 将字符串连接在一起的尝试将不起作用,因为这是在尝试执行除法。您在为源文件创建完整路径时正确使用了os.path.join,您只需对目标文件也执行相同的操作。

import shutil
import os

src_path = "path of source directory"
dst = "path of destination directory"

for file in os.listdir(src_path):
    file_path = os.path.join(src_path, file)
    shutil.copy(file_path, os.path.join(dst, "new-" + file))

【讨论】:

    【解决方案2】:

    任何时候你想在 Python 3 中操作路径,我觉得你应该联系pathlib。这是一个使用shututilcopytree 和使用pathlib 的自定义复制功能的解决方案。这很好,因为它也适用于嵌套目录 - 请注意,它不会重命名目录,只重命名文件:

    from pathlib import Path
    import shutil
    
    
    def copy_and_rename(src: str, dst: str):
        """copy and rename a file as new-<name>"""
        new_name = "new-" + Path(dst).name
        new_dst = Path(dst).with_name(new_name)
        shutil.copy2(src, new_dst)
    
    
    shutil.copytree(
        "./copy-from-me", "./copy-to-me", copy_function=copy_and_rename, dirs_exist_ok=True
    )
    

    下面是一个运行示例:

    $ tree copy-from-me
    copy-from-me
    ├── 1.txt
    ├── 2.txt
    └── nested
        └── 3.txt
    
    $ tree copy-to-me
    copy-to-me
    ├── nested
    │   └── new-3.txt
    ├── new-1.txt
    └── new-2.txt
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 2021-09-02
      • 2017-12-11
      • 2011-02-15
      相关资源
      最近更新 更多