Reputation: 2014
I have 100 txt files in a folder (named as pos). I would like to copy all the file contents and paste them as rows in an excel file. I found some codes from stackoverflow, but they are not working. Please help me.
import xlwt
import os
import glob
wbk = xlwt.Workbook()
sheet = wbk.add_sheet('data')
path= 'C:\tweet\pos'
row = 0
for files in os.walk(path):
... for file in files:
... if fnmatch(file, '*.txt'):
... L = open(os.path.join( file), "r").read()
... sheet.write(row,5,L)
... row += 1
...
wbk.save('read_all_txt_in_folders.xls')
Upvotes: 4
Views: 3392
Reputation: 168716
The following program works for me.
Notes:
'\t'
is being interpreted as a tab, not a path delimiter. Try using forward slashes.import fnmatch
/ fnmatch.fnmatch(pattern, file)
. glob
is not required.L[:-1]
was sufficient. You may require a more robust solution.os.walk()
returns a tuple: (directory, subdirectories, files)
..
import xlwt
import os
import fnmatch
wbk = xlwt.Workbook()
sheet = wbk.add_sheet('data')
row = 0
# sheet.write(1, 1, "Hello")
for (dir, dirs, files) in os.walk('.'):
# print dir
for file in files:
# print " ", file
if fnmatch.fnmatch(file, '*.txt'):
L = open(os.path.join(dir, file), "r").read()
# print " ", L.__repr__()
a = sheet.write(row,5,L[:-1])
# sheet.write(row, 4, "hello")
# print " ", a
row += 1
wbk.save('read_all_txt_in_folders.xls')
Upvotes: 2