2012-11-23 147 views
0

我试图与此代码的文件夹中,以合并多个TXT的文件,但它不工作:Python的合并多个txt文件

import os,shutil 
path = "C:/Users/user/Documents/MergeFolder" 
f=open(path + "/fileappend.txt","a") 
for r,d,fi in os.walk(path): 
    for files in fi: 
     if files.endswith(".txt"):       
       g=open(os.path.join(r,files)) 
       shutil.copyfileobj(g,f) 
       g.close() 
f.close() 

任何人有一个想法?

+1

它不能正常工作...你可以指定详细信息,,你的目的地是否被覆盖 – avasal

+0

没有任何东西被覆盖或为我生成 –

+1

我很困惑,看到'/ tmp'和'C:\ users'在相同的代码中。你所在的系统是什么?另外,写'r“C:\ Users ...”'来代替,以防止逃跑。 – bereal

回答

1

编辑:您正在创建fileappend.txt里面path,同时写入它。取决于将写入刷新到磁盘的时间,您可能正在尝试读取要附加到的文件。这会造成很多奇怪的现象。考虑不要将fileappend.txt放入path之内,否则只要在完成后将它移动到那里。

你可以更巧妙地编写代码为:

with open(os.path.join(path, "fileappend.tmp"), "a") as dest: 
    for _, _, filenames in os.walk(path): 
     for filename in fnmatch.filter(filenames, "*.txt"): 
      with open(filename) as src: 
       shutil.copyfileobj(src, dest) 
os.rename(os.path.join(path, "fileappend.tmp"), "fileappend.txt") 
+0

嗨,我试过你的代码,但得到了这个:NameError:全球名称'fnmatch'未定义 –

+0

您需要'导入fnmatch'。 – katrielalex

+0

现在我得到这个:IOError:[Errno 2]没有这样的文件或目录:'fileappend.txt',但文件存在没有内容。 –

0

您可以使用cat(shell命令)

cat 1.txt>>2.txt 
在Python

,您可以使用使用os.system()使用shell命令