kevin
kevin

Reputation: 2014

How to read all text file contents in a folder and copy those contents as rows into one excel file

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

Answers (1)

Robᵩ
Robᵩ

Reputation: 168716

The following program works for me.

Notes:

  • The '\t' is being interpreted as a tab, not a path delimiter. Try using forward slashes.
  • It is import fnmatch / fnmatch.fnmatch(pattern, file). glob is not required.
  • I had to remove the trailing newlines from the strings. In my test case, using L[:-1] was sufficient. You may require a more robust solution.
  • os.walk() returns a tuple: (directory, subdirectories, files).
  • I have left my debugging statements in comments in case they help you.

.

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

Related Questions