python 合并文件夹下所有子文件夹里的txt 文件

import glob
import os
def test():
path='/Users/apple/Desktop/SMJ/'
listing=os.listdir(path)
for i in listing:
print ('current file is:' + i)
read_files=glob.glob('*.txt')
with open('result.txt', 'wb') as outfile:
for f in read_files:
with open(f,'rb') as infile:
outfile.write(infile.read())

这个应该是进入了SMJ下的所有文件夹,但是出来的合并所有txt的大txt每次都是空的。为什么呢?求助!谢谢!
import glob
import os
def test():
read_files=glob.glob('Users/apple/Desktop/SMJ/*.txt')
with open('result.txt', 'wb') as outfile:
for f in read_files:
with open(f,'rb') as infile:
outfile.write(infile.read())

第1个回答  2014-08-11
listdir不是进入而是相当于终端命令ls。。
read_files=glob.glob('/Users/apple/Desktop/SMJ/
*.txt')

就可以了。追问

我刚才试了一下,把代码改成了补充问题中的样子。但还是出来了一个空的txt。求助!

追答import glob
import os
def test():
read_files=glob.glob('/Users/apple/Desktop/SMJ/*.txt')
with open('/Users/apple/Desktop/SMJ/result.txt', 'wb') as outfile:
for f in read_files:
with open(f,'rb') as infile:
outfile.write(infile.read())
test()

追问

跑程序的第一秒钟出现了一个有字的txt,之后马上又变成了空白。

追答

额。现在我也不知道了。。我这边是成功了。。

本回答被提问者采纳