无法在 Python 中列出过滤后的目录内容:(需要字符串,已找到 posix)
Trouble listing filtered directory contents in Python: (need string, posix found)
我不确定我做错了什么,因为我从另一个 SO 建议中采用了这种方法。
import os
import pathlib
import sys
import re
source = sys.argv[1]
directory = pathlib.Path(source).parent
res = [f for f in os.listdir(directory) if re.search(r'.+_page_\d\.pdf', str(f))]
print res
我收到以下错误:
Traceback (most recent call last):
File "merge_pdfs.py", line 12, in <module>
res = [f for f in os.listdir(directory) if re.search(r'.+_page_\d\.pdf', str(f))]
TypeError: coercing to Unicode: need string or buffer, PosixPath found
listdir
的结果不应该是一个字符串列表吗?我怎么会收到这个错误?
尝试添加斜线
directory = "{}/".format(directory)
我不确定我做错了什么,因为我从另一个 SO 建议中采用了这种方法。
import os
import pathlib
import sys
import re
source = sys.argv[1]
directory = pathlib.Path(source).parent
res = [f for f in os.listdir(directory) if re.search(r'.+_page_\d\.pdf', str(f))]
print res
我收到以下错误:
Traceback (most recent call last):
File "merge_pdfs.py", line 12, in <module>
res = [f for f in os.listdir(directory) if re.search(r'.+_page_\d\.pdf', str(f))]
TypeError: coercing to Unicode: need string or buffer, PosixPath found
listdir
的结果不应该是一个字符串列表吗?我怎么会收到这个错误?
尝试添加斜线
directory = "{}/".format(directory)