0

I have a folder containing multiple files and I am looking for a file that contains only "Low" and "1 Hour". So to read all those file addresses I am using the glob library.

import glob
path = glob.glob("summary output\*.xlsx")
print(path)

output:

summary output\2030 and 2030 High RE with 1 Hour storage.xlsx
summary output\2030 and 2030 High RE with 2 Hour storage.xlsx
summary output\2030 and 2030 High RE with 4 Hour storage.xlsx
summary output\2030 and 2030 High RE with 6 Hour storage.xlsx
summary output\2030 and 2030 Low RE with 1 Hour storage.xlsx
summary output\2030 and 2030 Low RE with 2 Hour storage.xlsx
summary output\2030 and 2030 Low RE with 4 Hour storage.xlsx
summary output\2030 and 2030 Low RE with 6 Hour storage.xlsx

These are the list of files in that summary output folder. Now I want a file which contains Low and 1 Hour, basically this file:

summary output\2030 and 2030 Low RE with 1 Hour storage.xlsx

so for this I wrote this:

for file in path:
    if "Low"  and "1 Hour" in file:
        print(file)

output:

summary output\2030 and 2030 High RE with 1 Hour storage.xlsx
summary output\2030 and 2030 Low RE with 1 Hour storage.xlsx

I don't know why its taking the first file so can anyone please help?

Vesper
  • 795
  • 1
  • 9
  • 21

3 Answers3

1

Try this

for file in path:
if "Low"  in file and "1 Hour" in file:
    print(file)
Ajay A
  • 1,030
  • 1
  • 7
  • 19
1

Couldn't comment so here's my 2cents anyway.

Try

If "Low" in file and "1 Hour" in file:
     Print file

Right now the way your condition is working is-

"Low" and ("1 Hour" in file)

Also check this- 'and' (boolean) vs '&' (bitwise) - Why difference in behavior with lists vs numpy arrays?

On the other hand you could let your wildcard do the work for you-

glob.glob("summary output\*Low*1*.xlsx")
sai
  • 1,734
  • 1
  • 7
  • 13
1
for file in path:
    #The below line is not checking for 'Low' substring in path, but checking if "Low" is equal to None, so it always returns True.
    if "Low"  and "1 Hour" in file:  
        print(file)
Blossom
  • 113
  • 1
  • 8