【问题标题】:python 2.6 TypeError: coercing to Unicode: need string or buffer, list foundpython 2.6 TypeError:强制转换为Unicode:需要字符串或缓冲区,找到列表
【发布时间】:2014-05-07 11:42:53
【问题描述】:

我不明白这个 TypeError 的原因

脚本:

import os
import shutil

src1 = os.listdir("/usr/dir1")
dst1 = os.listdir("/usr/dir2")


for file in src1:
    if file not in dst1:
        shutil.copy(file, dst1)

错误:

File "/scripts/trans_dir_balancing.py", line 14, in <module>
    shutil.copy(file, dst1)
  File "/usr/lib64/python2.6/shutil.py", line 82, in copy
    if os.path.isdir(dst):
  File "/usr/lib64/python2.6/genericpath.py", line 41, in isdir
    st = os.stat(s)
TypeError: coercing to Unicode: need string or buffer, list found

感谢帮助

【问题讨论】:

    标签: python unicode python-2.6


    【解决方案1】:

    因为您的代码中的 dst1 不是路径,而是路径列表。它应该是路径(字符串),请查看shutil.copy()os.listdir()

    【讨论】:

      【解决方案2】:

      假设您试图将文件从一个文件夹复制到另一个文件夹,您只需将目标目录指定为 shuti.copy 中的第二个参数。

      import os
      import shutil
      
      src = '/usr/dir1'
      dst = '/usr/dir2'
      
      for file in os.listdir(src):
          if file not in os.listdir(dst) and os.path.isfile(file):
              # copy file to dst dir if not exists
              shutil.copy(os.path.join(src, file), dst)
      

      【讨论】:

      • 如果在源目录中找到目录,这将引发IOError: [Errno 21],这就是为什么需要if os.path.isfile(file):。另外值得一提的是,OP 正在覆盖内置的 file 对象,并且应该重命名变量。
      • 好点。对于第 1 点,除非有可能发生,否则我认为程序不需要过于复杂。尽管我将编辑代码以提及以防 OP 不知道。谢谢。
      • 此代码存在不安全的竞争条件。通过依赖if file not in os.listdir(dst),您假设在对shutil.copy 的以下调用之前无法在目标目录中创建目标文件名,这通常不是真的。由于shutil.copy 会覆盖现有文件,因此这是不安全的。您应该考虑使用不覆盖的不同 API,并跳过存在性检查,转而使用 try/except 块来处理覆盖条件。
      【解决方案3】:

      我知道这篇文章已经过时了。然而,我发现几个月后我正在做一个类似的项目很有趣。我正在开发一个程序来备份我的主目录。 我就是这样做的。

      for root, dirs, files in os.walk(r'input path of files to be backed up'):
      for ckfile in files:
          for root2, dirs2, files2 in os.walk(r'input your destination directory'):
              if ckfile not in files2:
                  print"Backing up the file "+ckfile
                  copyf = os.path.join(root,ckfile)
                  shutil.copy2(copyf, r'input your destination directory')    
              else:
                  print "The file "+ckfile+" is already backed up"
      

      现在,我需要一种检查本机压缩的方法。我考虑过使用 zip,但这需要我更改到目前为止的代码。我可能只是要让程序测试一下是否正在使用什么操作系统,然后使用该操作系统命令来压缩文件。

      【讨论】:

        猜你喜欢
        • 2014-03-02
        • 1970-01-01
        • 2017-03-31
        • 1970-01-01
        • 1970-01-01
        • 2021-03-28
        • 2015-02-01
        • 2014-12-21
        • 1970-01-01
        相关资源
        最近更新 更多