Python: Cannot copy file TypeError: coercing to Unicode: need string or buffer, file found

Python: Cannot copy file TypeError: coercing to Unicode: need string or buffer, file found

我有一个名为 "default_xxx.txt" 的文本文件列表,例如:default_abc.txt、default_def.txt 我想将文件内容复制到另一个文件,即 name "xxx.txt" 去掉 "default_".

参考下面Python中复制文件的回答: How do I copy a file in python? 这是我的代码:

import os
import shutil
import re
for root, dirs, files in os.walk("../config/"):
    for file in files:
        if file.endswith(".txt") and file.startswith("default_"):
            file_name = os.path.basename(os.path.join(root, file))
            file_name = re.sub(r'default_','',file_name)
            config_file = open(os.path.join(root,file_name), 'w+') 
            shutil.copy(file,config_file)
我收到一个错误:

Traceback (most recent call last):
  File "C:\gs2000_IAR\tools\automation\lib\test.py", line 11, in <module>
    shutil.copy(file,config_file)
  File "C:\Python27\lib\shutil.py", line 117, in copy
    if os.path.isdir(dst):
TypeError: coercing to Unicode: need string or buffer, file found

非常感谢任何人的帮助。

根据 documentationshutil.copy 收到 文件名 ,而不是内容。报错信息其实很清楚这种不匹配。

所以倒数第二行应该是:

config_file = os.path.join(root,file_name)

正如错误消息所说, shutil.copy 接受字符串:文件 names (嗯,路径),而不是打开文件对象。所以不要打开文件。

shutil.copy(file, os.path.join(root,file_name))

您将文件句柄作为参数而不是文件名发送给 copyopen 创建并 returns 文件句柄而不是名称,这是您不想要的。只是失去对 open.

的呼叫
import os
import shutil
import re
for root, dirs, files in os.walk("../config/"):
    for file in files:
        if file.endswith(".txt") and file.startswith("default_"):
            file_name = os.path.basename(os.path.join(root, file))
            file_name = re.sub(r'default_','',file_name)
            config_filename = os.path.join(root,file_name)
            shutil.copy(file,config_filename)

我认为您有命名冲突。 'file' 是一个 python 函数,因此您可能希望将变量重命名为 'file'.