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,subdi开发者_如何学Pythonr,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. L
contains the file name. (And the L = 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()
.
If you want to write the file contents, you should do instead
with open(os.path.join(dir, file), "r") as source:
L= source.read()
This assures that the file is actually closed when you're done reading them. That releases system resources.
精彩评论