从嵌套文件夹将.txt转换为.xls

时间:2015-10-21 09:49:45

标签: python excel

我找到了一个将.txt转换为.xls的Python脚本,它正在运行:Converting multiple tab-delimited .txt files into multiple .xls files

import glob
    import csv
    import xlwt
    import win32com.client as win32
for filename in glob.glob("C:\Users\MSI\Desktop\Python Lab\AGR\\*.txt"):
    spamReader = csv.reader((open(filename, 'rb')), delimiter='|',quotechar='"')
    encoding = 'latin1'
    wb = xlwt.Workbook(encoding=encoding)

    sheet=xlwt.Workbook()
    sheet = wb.add_sheet('sheet 1')
    newName = filename
    for rowx, row in enumerate(spamReader):
        for colx, value in enumerate(row):
            sheet.write(rowx, colx, value)

    wb.save(newName.replace('.txt','.xls'))

print "Done"  

但是,它只能转换文件路径,但无法转换嵌套文件夹中的任何文件。

我如何修改它以包含嵌套文件夹?

1 个答案:

答案 0 :(得分:1)

以下内容应该有效。它使用Python的os.walk函数遍历所有子文件夹:

import xlwt
import os

path = r'C:\Users\MSI\Desktop\Python Lab\AGR'

for root, dirs, files in os.walk(path):
    for filename in files:
        name, ext = os.path.splitext(filename)
        if ext.lower() == '.txt':
            source = os.path.join(root, filename)
            dest = os.path.join(root, name + '.xls')

            with open(source, 'rb') as f_input:
                spamReader = csv.reader(f_input, delimiter='|',quotechar='"')
                wb = xlwt.Workbook(encoding='latin1')
                sheet = xlwt.Workbook()
                sheet = wb.add_sheet('sheet 1')

                for rowx, row in enumerate(spamReader):
                    for colx, value in enumerate(row):
                        sheet.write(rowx, colx, value)

                wb.save(dest)

print "Done"