python读取一个目录下所有txt里面的类容
python读取一个目录下所有txt里面的类容
比如有个目录d:\project这个文件夹,在这个文件夹下面有N个txt,获得每个txt里面的类容怎么取
[解决办法]
Python3.3
import os
from os.path import join
def main() :
dest = "d:/project/"
outfile = open( "output.txt", "w" )
for root, dirs, files in os.walk( dest ):
for OneFileName in files :
if OneFileName.find( '.txt' ) == -1 :
continue
OneFullFileName = join( root, OneFileName )
for line in open( OneFullFileName ):
print( line, end = '' )
if __name__ == "__main__" :
main()
>>> import glob
>>> glob.glob('./[0-9].*')
['./1.gif', './2.txt']
>>> glob.glob('*.gif')
['1.gif', 'card.gif']
>>> glob.glob('?.gif')
['1.gif']
# -*- coding:utf-8 -*-
import glob
txt_filenames = glob.glob('d:\\project\\*.txt')
for filename in txt_filenames:
txt_file = open(filename, 'r')
buf = txt_file.read() # the context of txt file saved to buf
txt_file.close()