How can i check if each file in a listdir contains a specific file?

by okeyiaj   Last Updated September 11, 2019 19:26 PM - source

Sorry this is my first post so please bare with me.

My goal is to check each item in my list, os.listdir(folder), and if the folder contains an .xlsx, I then want to append the name of each folder and name of the each excel file for each listdir, to an empty list so the finished list would look something like this: [('Name of the folder1', 'Name of the excel file1'),('Name of the folder2', 'Name of the excel file2'), ...]

my attempt was

import os

def main():
array = []
filenames = os.listdir('code\\folder')
for i in filenames:
    list = os.listdir('code\\folder\\{}'.format(i))
    try:
        excelfilename = list(filter(lambda x: x.endswith('.xlsx'), list))[0]
        array.append((i, excelfilename))
   except:
        array.append((i, 'No excel file'))

main()

However I am getting some errors and unfortunately the program isn't running

I would love if you could help

Thanks :)

Tags : python


Related Questions


Images dimensions error in python

Updated February 24, 2018 05:26 AM



How to test Python 3.4 asyncio code?

Updated July 28, 2017 22:26 PM