pythonpathtypeerrorpython-3.4

Why is path.name() in python 3.4 giving me "TypeError: 'str' object is not callable"?


The following code is just trying to print the name of all files in a directory:

from pathlib import Path

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

It gives me the error:

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

If I print the "myPath" object type, everything in the directory returns class pathlib.windowspath.

I'm using Python 3.4 on Windows 8 in the latest version of parallels.


Solution

  • myPath.name isn't callable, because it's an attribute of str type. Try this instead:

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