首页 > 解决方案 > 在 OSX 上的 python3 中使用 Path.glob 查找带有 unicode 字符的文件

问题描述

如何在 OSX 上找到以“dec2file”开头且具有扩展名的文件名?

就我而言,我在 Documents 目录中只有一个 .ppt 文件。所以,结果应该是:dec2file.ppt

这是代码:

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))

当前结果:

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

我如何让它找到文件并打印:

Found it - dec2file.ppt

标签: pythonmacososx-yosemite

解决方案


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.


推荐阅读