-1

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

Kalyan N
  • 57
  • 6
  • 2
    Well, where the code does `print(csv_files)`, do you see the files that should be matched? Where the code says `res = [ele for ele in groups1 if(ele in csv_files)]`, what is `groups1`? What does that have to do with the outer `for group in groups:` loop? Does `groups` look like what you expect it to? What do you expect the `ele` values to look like, and why should it be the case that `ele in csv_files`? Please read https://ericlippert.com/2014/03/05/how-to-debug-small-programs/. – Karl Knechtel Jun 10 '22 at 12:13
  • Sorry for not articulating the question in the right way. – Kalyan N Jun 10 '22 at 12:39
  • The problem is not how the question is articulated. The problem is that you are [expected](https://meta.stackoverflow.com/questions/261592) to study the code before asking. I did not ask the questions to rebuke you. I asked the questions because you should try to answer them, because it should help you find the problem. If you still have a problem after trying those steps, please [edit] the question to reflect your new understanding. – Karl Knechtel Jun 10 '22 at 12:49

1 Answers1

1

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"))
GordonAitchJay
  • 4,640
  • 1
  • 14
  • 16
  • Thank you so much. I'm beginner in python programming and this solution seems so basic i couldn't figure it out. It worked thanks alot. – Kalyan N Jun 10 '22 at 12:36