I am currently working on this task and got stuck. Please give me your advices. The code I am writing below, it returns only the .txt file name from multiple folders, while I would like to print out the content of each .txt file and save in different rows in excel. The contents of each .txt file are numbers.
import os, glob,xlwt
#create workbook and worksheet
wbk = xlwt.Workbook()
sheet = wbk.add_sheet('data')
path= 'E:\Cag\Data'
row = 0
for dir,subdir,files in os.walk(path):
for file in files:
if glob.fnmatch.fnmatch(file, '*.txt'):
L = file.strip()
sheet.write(row,5,L)
row += 1
wbk.save('read_all_txt_in_folders.xls')
print 'success'
Well, you see the file names because you write them.
Lcontains the file name. (And theL = file.strip()seems unnecessary to me.)If you want to write the file contents, you should do instead
L = open(os.path.join(dir, file), "r").read().