首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

python读取一个目录上所有txt里面的类容

2013-01-11 
python读取一个目录下所有txt里面的类容python读取一个目录下所有txt里面的类容比如有个目录d:\project这

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()

[解决办法]
可以试试glob
>>> 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()

热点排行