Fix AttributeError: ‘PosixPath’ object has no attribute ‘split’ – Python Tutorial

By | July 28, 2021

In python, we can use python pathlib package to get file path or traverse files in a directory. Here are tutorials:

Python pathlib: Traverse Files in a Directory – Python Tutorial

Python pathlib Guide: Get File Path Information

However, the file path is ‘PosixPath’, we can not process it as a python string. Here is an example:

def getFiles(path='./datax/500ms', filetype = ".bin"):
    files = pathlib.Path(path).glob('*'+filetype)
    return files
files = getFiles()
for fx in files:
    fx = fx.split("-")

Run this code, you may get this error:

AttributeError: ‘PosixPath’ object has no attribute ‘split’

How to fix this AttributeError?

It is easy to fix this error, we can convert PosixPath to python string.

Here is an example:

for fx in files:
    fx = str(fx)
    fx = fx.split("-")

Then, you will find this error is fixed.

Leave a Reply