为什么 python 3.4 中的 path.name() 给我“TypeError: 'str' object is not callable”?

问题描述 投票:0回答:2

以下代码只是尝试打印目录中所有文件的名称:

from pathlib import Path

for myPath in Path.cwd().iterdir():
    print (myPath.name())

它给了我错误:

Traceback (most recent call last):
    File "NameTest.py", line 4, in <module>
        print (myPath.name())
TypeError: 'str' is not callable

如果我打印“myPath”对象类型,目录中的所有内容都会返回类pathlib.windowspath。

我在 Windows 8 上的最新版本的并行中使用 Python 3.4。

python path typeerror python-3.4
2个回答
3
投票

myPath.name
不可调用,因为它是 str 类型的
attribute
。 试试这个:

for myPath in Path.cwd().iterdir():
    print(myPath.name)

0
投票

@大卫·马多克斯, 兄弟,我也犯过和你一样的错误。当我想处理绝对路径:

'C:\\Users\\109_IR\\2023_06_15_09_43_53_078.jpg'
pathlib
Path()
时,我得到了和你一样的回溯错误。事实证明,我们可以在
 中放入像 
str
 这样的 
'C:\\Users\\109_IR\\2023_06_15_09_43_53_078.jpg'
 变量Path()
。我的错误原因是我的代码前面有一个名为 Path 的变量。这会导致在
Path()
中调用
pathlib
函数时出错。这显然是一个简单的错误,希望没有主体不然也会犯和我一样的错误

© www.soinside.com 2019 - 2024. All rights reserved.