Python:无法复制文件TypeError:强制转换为Unicode:需要字符串或缓冲区,找到文件

时间:2015-01-20 23:31:30

标签: python file unicode

我有一个名为“default_xxx.txt”的文本文件列表,例如:default_abc.txt,default_def.txt 我想将文件内容复制到另一个文件,名称为“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

非常感谢任何人的帮助。

4 个答案:

答案 0 :(得分:0)

根据documentationshutil.copy收到文件名,而不是内容。错误信息实际上非常清楚这种不匹配。

所以你的倒数第二行应该只是:

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

答案 1 :(得分:0)

正如错误消息所示, shutil.copy需要字符串:文件名称(以及路径),而不是打开文件对象。所以不要打开文件。

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

答案 2 :(得分:0)

您将文件句柄作为参数发送到copy而不是文件名。 open创建并返回文件句柄,而不是您不想要的名称。只是失去对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)

答案 3 :(得分:0)

我认为你有一个命名冲突。 &#39;文件&#39;是一个python函数,因此您可能希望重命名变量&#39; file&#39;。