简体   繁体   English

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

[英]Convert .txt to .xls from nested folders

I found a Python script to convert .txt to .xls and it is working: Converting multiple tab-delimited .txt files into multiple .xls files : 我发现了一个Python脚本,可以将.txt转换为.xls,并且可以正常工作: 将多个制表符分隔的.txt文件转换为多个.xls文件

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"  

However, it can only convert the file path but could not convert any files in nested folders. 但是,它只能转换文件路径,而不能转换嵌套文件夹中的任何文件。

How I may modify it to include nested folders? 如何修改它以包含嵌套文件夹?

Something like the following should work. 像下面这样的东西应该起作用。 It uses Python's os.walk function to traverse all sub folders: 它使用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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM