Home > Back-end >  Compare lines in TXT file to excel file name in a directory using python
Compare lines in TXT file to excel file name in a directory using python

Time:06-11

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

CodePudding user response:

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"))
  • Related