![](/img/trans.png)
[英]Path.glob bring <class generator>, not real file path
[英]finding file with unicode characters using Path.glob in python3 on OSX
如何在 OSX 上找到以“dec2💜file”开头的文件名?
就我而言,我在 Documents 目录中只有一个 .ppt 文件。 所以,结果应该是:dec2💜file.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
的文件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 - test\dec2💜file.txt
因此,我只能得出结论,在运行脚本的工作目录中没有名为Documents
文件夹。 尝试用完整路径名替换my_pathname
,或确保您的脚本在Documents
的父目录中运行。
您可以通过从 IDE 或在命令行中更改脚本的工作目录,或使用os.chdir
或类似更改脚本相关部分之前的目录来完成此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.