Compare lines in TXT file to excel file name in a directory using python

Issue

I have a TXT file which consists of names. I wanted to compare line from txt file to excel file name in the directory. Ex: TXT file name contains

Johny
Wick
Rick

I wanted to compare first line in TXT file Johny with the existing excel file name in directory such as Johny.xlsx and select the absolute path of the file for further use. Please suggest on how to achieve this in python. So far i can do this

with open('groups.txt', 'r', encoding='utf8') as f:
        groups = [group.strip() for group in f.readlines()]
path = os.getcwd()
csv_files = glob.glob(os.path.join(path, "*.xlsx"))
print(csv_files)

for group in groups:
res = [ele for ele in groups1 if(ele in csv_files)]

print("Does string contain any list element : " + str(res))

Its not able to find the matching excel file. Please help

Solution

Why do you need to call glob.glob if all the excel files are in the same directory as the textfile with names in it?

This will give you the absolute filepath for the excel files, assuming they exist if the group name is in the textfile.

for group in groups:
    # Use an f-string
    print(os.path.join(path, f"{group}.xlsx"))
    
    # Or append add strings together
    # print(os.path.join(path, group + ".xlsx"))

Answered By – GordonAitchJay

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published