在OSX上使用python3中的Path.glob查找带有Unicode字符的文件



如何找到以"dec2💜file"开头且在 OSX 上具有扩展名的文件名?

就我而言,我在文档目录中只有一个.ppt文件。因此,结果应该是: dec2💜文件.ppt

这是代码:

my_pathname='Documents'
my_filename='dec2💜file'
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))

当前结果:

ERROR - Documents/dec2💜file.* - list index out of range

如何获取它以查找文件并打印:

Found it - dec2💜file.ppt

在创建一个名为test的文件夹和其中一个名为dec2💜file.txt的文件后,我运行了这个:

import pathlib
my_pathname = 'test'
my_filename = 'dec2💜file'
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))

并得到:

Found it - testdec2💜file.txt

因此,我只能得出结论,在运行脚本的工作目录中没有名为Documents的文件夹。尝试将my_pathname替换为完整路径名,或确保脚本在Documents的父目录中运行。

为此,可以从 IDE 或在命令行上更改脚本的工作目录,或者使用os.chdir或类似方法在脚本的相关部分之前更改目录。

最新更新