2

First of all thanks for reading this. I am a little stuck with sub directory walking (then saving) in Python. My code below is able to walk through each sub directory in turn and process a file to search for certain strings, I then generate an xlsx file (using xlsxwriter) and post my search data to an Excel.

I have two problems...

The first problem I have is that I want to process a text file in each directory, but the text file name varies per sub directory, so rather than specifying 'Textfile.txt' I'd like to do something like *.txt (would I use glob here?)

The second problem is that when I open/create an Excel I would like to save the file to the same sub directory where the .txt file has been found and processed. Currently my Excel is saving to the python script directory, and consequently gets overwritten each time a new sub directory is opened and processed. Would it be wiser to save the Excel at the end to the sub directory or can it be created with the current sub directory path from the start?

Here's my partially working code...

for root, subFolders, files in os.walk(dir_path):
    if 'Textfile.txt' in files:
        with open(os.path.join(root, 'Textfile.txt'), 'r') as f:

            #f = open(file, "r")    
            searchlines = f.readlines()
            searchstringsFilter1 = ['Filter Used          :']
            searchstringsFilter0 = ['Filter Used          : 0']

            timestampline = None
            timestamp = None
            f.close()

            # Create a workbook and add a worksheet.
            workbook = xlsxwriter.Workbook('Excel.xlsx', {'strings_to_numbers': True})
            worksheetFilter = workbook.add_worksheet("Filter")

Thanks again for looking at this problem.

MikG

4

2 回答 2

1

我不会完全解决您的代码,但这里有一些提示:

文本文件名因子目录而异,因此我不想指定“Textfile.txt”,而是执行 *.txt 之类的操作

您可以列出目录中的所有文件,然后检查文件扩展名

for filename in files:  
  if filename.endswith('.txt'):  
    # do stuff

另外在创建工作簿时,您可以输入路径吗?你有根,对吧?为什么不使用它?

于 2014-06-12T14:01:54.253 回答
0

您不想要 glob,因为您已经在files变量中有一个文件列表。因此,过滤它以查找所有文本文件:

import fnmatch
txt_files = filter(lambda fn: fnmatch.fnmatch(fn, '*.txt'), files)

要将文件保存在同一子目录中:

outfile = os.path.join(root, 'someoutfile.txt')
于 2014-06-12T14:44:40.273 回答