2015-01-20 63 views
0

我有一個名爲「default_xxx.txt」的文本文件列表,例如:default_abc.txt,default_def.txt 我想將文件內容複製到另一個名爲「xxx.txt」的文件中,刪除「default_」。Python:無法複製文件TypeError:強制爲Unicode:需要字符串或緩衝區,找到文件

參考複製的文件在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

任何人的幫助將非常感激。

+0

請使用{}按鈕格式化代碼。謝謝! – dylrei 2015-01-20 23:33:33

+0

您可能需要copyfileobj()。請參閱:https://docs.python.org/2/library/shutil.html – dylrei 2015-01-20 23:36:54

回答

0

隨着錯誤消息指出,shutil.copy需要字符串:文件(當然,路徑),不能打開文件對象。所以不要打開文件。

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

根據documentationshutil.copy收到文件名,而不是內容。錯誤信息實際上非常清楚這種不匹配。

所以你下到最後一行應該只是:

config_file = os.path.join(root,file_name) 
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) 
0

我認爲你有一個命名衝突。 'file'是一個python函數,所以你可能想重命名變量'file'。

+0

雖然不掩蓋這個名稱是很好的,但這與此處的問題無關。 – 2015-01-20 23:41:45

相關問題