我有一个名为“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
非常感谢任何人的帮助。
答案 0 :(得分:0)
根据documentation,shutil.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;。