finding file with unicode characters using Path.glob in python3 on OSX

559 Views Asked by At

How do I find a filename starting with "dec2file" that has an extension on OSX?

In my case, I have only one .ppt file in the Documents directory. So, the result should be: dec2file.ppt

Here is the code:

my_pathname='Documents'
my_filename='dec2file'
my_glob = "{c}.{ext}".format(c=my_filename, ext='*')
try:
  my_filename = str(list(pathlib.Path(my_pathname).glob(my_glob))[0])
except Exception as ex:
  print("Error - {d}/{f} - {e}".format(d=my_pathname, f=my_glob, e=str(ex)))
  exit(1)
print("Found it - {f}".format(f=my_filename))

Current result:

ERROR - Documents/dec2file.* - list index out of range

How do I get it to find the file and print:

Found it - dec2file.ppt
1

There are 1 best solutions below

2
Grismar On

After creating a folder called test, and a file inside it called dec2file.txt, I ran this:

import pathlib

my_pathname = 'test'
my_filename = 'dec2file'
my_glob = "{c}.{ext}".format(c=my_filename, ext='*')

try:
    my_filename = str(list(pathlib.Path(my_pathname).glob(my_glob))[0])
except Exception as ex:
    print("Error - {d}/{f} - {e}".format(d=my_pathname, f=my_glob, e=str(ex)))
    exit(1)


print("Found it - {f}".format(f=my_filename))

And got:

Found it - test\dec2file.txt

So, I can only conclude there is no folder called Documents inside the working directory where your script runs. Try replacing my_pathname with a full path name, or ensure your script runs in the parent directory of Documents.

You can do this by either changing the working directory of the script from your IDE or on the command line, or by using os.chdir or something similar to change directory before the relevant part of the script.