3 回答

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超8個(gè)贊
startswith()是一個(gè) Python 字符串方法,見https://python-reference.readthedocs.io/en/latest/docs/str/startswith.html
由于您的 f 是 Path 對(duì)象,因此您必須先將其轉(zhuǎn)換為字符串str(f)
def recursive_file_count(scan_path):
root_directory = Path(scan_path)
fcount = len([f for f in root_directory.glob('**/*') if str(f).startswith(".")])
print(fcount)

TA貢獻(xiàn)2003條經(jīng)驗(yàn) 獲得超2個(gè)贊
有一種startswith- 你可以使用pathlib.Path.is_relative_to():
pathlib.Path.is_relative_to()在 Python 3.9 中添加,如果您想在早期版本(3.6 以上)上使用它,您需要使用 backport pathlib3x:
$> python -m pip install pathlib3x
$> python
>>> p = Path('/etc/passwd')
>>> p.is_relative_to('/etc')
True
>>> p.is_relative_to('/usr')
False
但這對(duì)您的示例仍然無濟(jì)于事,因?yàn)槟胩^以“?!遍_頭的文件。- 所以你的解決方案是正確的 - 但不是很有效:
def recursive_file_count(scan_path):
root_directory = Path(scan_path)
fcount = len([f for f in root_directory.glob('**/*') if not str(f.name).startswith(".")])
print(fcount)
想象一下,您在scan_path中有 200 萬個(gè)文件,這將創(chuàng)建一個(gè)包含 200 萬個(gè) pathlib.Path 對(duì)象的列表。哇,這需要一些時(shí)間和記憶......
最好有一種像 fnmatch 這樣的過濾器或用于 glob 函數(shù)的東西——我正在考慮將它用于 pathlib3x。
Path.glob() 返回一個(gè)生成器迭代器,它需要更少的內(nèi)存。
所以為了節(jié)省內(nèi)存,解決方案可以是:
def recursive_file_count(scan_path):
root_directory = Path(scan_path)
fcount = 0
# we only have one instance of f at the time
for f in root_directory.glob('**/*'):
if not str(f.name).startswith(".")]):
fcount = fcount + 1
print(count)

TA貢獻(xiàn)1936條經(jīng)驗(yàn) 獲得超7個(gè)贊
我的解決方案:
def recursive_file_count(scan_path):
root_directory = Path(scan_path)
fcount = len([f for f in root_directory.glob('**/*') if not str(f.name).startswith(".")])
print(fcount)
添加回答
舉報(bào)