python - 在 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
解决方案
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.
推荐阅读
- android - 从 https://dl.google.com/ 在 macos 上下载失败的原因可能是什么
- batch-file - 批处理文件过滤 ping 结果并附加 .csv
- c - 使用 DT_FILTER 隐藏 DSO 中的符号
- r - 当列表是动态的时,在列表中查找变量的特定项目
- cassandra - cassandra 购物车数据建模讲解
- python - 如何在每一行中添加制表符?
- sql-server - SQL Server - 映射表以识别要汇总的字段
- java - 没有为片段 HomeFragment{xx}(xxxx id=0x7f0800be tag=HomeFragment)找到 id 0x7f0800be (com.example.progetto:id/fragment_container_view) 的视图
- r - 如何使用 R 提取重叠栅格单元所在的多边形?
- python - 通过请求登录网站返回 403 错误