Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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"))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading