【问题标题】:Disable SameFileError exception in shutil.copy在 shutil.copy 中禁用 SameFileError 异常
【发布时间】:2019-07-17 20:22:37
【问题描述】:

我有以下代码,因为有时这些文件会相同,有时它们不会。

import shutil
try:
   shutil.copy('filea','fileb')
   shutil.copy('filec','filed')
except shutil.SameFileError
   pass

问题是如果第一个副本具有相同的文件,则不会发生第二个副本。

关于如何解决这个问题的任何建议?我在 shutil documentation 中没有看到禁用此检查的参数。

【问题讨论】:

    标签: python shutil


    【解决方案1】:

    您可以将复制调用分开:

    try:
       shutil.copy('filea','fileb')
    except shutil.SameFileError:
       pass
    
    try:
       shutil.copy('filec','filed')
    except shutil.SameFileError:
       pass
    

    或者把这四行放在一个函数中。

    【讨论】:

      【解决方案2】:

      没有一个非常优雅的解决方案。我真的不推荐这个解决方案。但这取决于你:)

      shutil._samefile 函数检查源文件和目标文件是否相同(它将始终被调用,因此副本没有任何停用它的选项)。如果返回值为True(所以文件是一样的),会抛出SameFileError异常(如下图)。

      if _samefile(src, dst):
          raise SameFileError("{!r} and {!r} are the same file".format(src, dst))
      

      您可以强制_samefile 函数在任何情况下都返回False

      import shutil
      
      
      def my_same_file_diff_checker(*args, **kwargs):
          return False
      
      
      shutil._samefile = my_same_file_diff_checker
      
      
      shutil.copy("test.ini", "test.ini")
      

      重要:

      使用此解决方案不会引发SameFileError,但会运行其他部分的复制功能。这意味着例如。文件的时间戳将被更新。如下图所示,文件的内容会被重写到文件中。

      with open(src, 'rb') as fsrc:
          with open(dst, 'wb') as fdst:
              copyfileobj(fsrc, fdst)
      

      其他(也许更优雅的)解决方案:

      • 我建议使用 2 个单独的 try-except(正如 @hko 所写)
      • 在复制之前检查文件的路径(可能是大多数 Pythonic 解决方案)。
      • 编写自己的复制函数/方法

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-08-03
        • 2016-02-21
        • 2015-07-28
        • 1970-01-01
        • 1970-01-01
        • 2010-10-07
        相关资源
        最近更新 更多