Getting error: AttributeError: 'str' object has no attribute 'append'

Question:

    import os
    find_ext = ('.txt',)

    file_paths = []
    for root, dirs, files in os.walk('C:\'):
        for file in files:
            file_paths, file_ext = os.path.splitext(root+'\'+file)
            if file_ext in find_ext:
                file_paths.append(root+'\'+file)

I keep getting AttributeError: 'str' object has no attribute 'append' and am not sure how to fix it.

Asked By: TheWizard

||

Answers:

You overwrite the file_path array with a string. The latter doesn’t have an append method as indicated by the error message. As you don’t have a use for the string just extract the file_ext:

import os
find_ext = ('.txt',)

file_paths = []
for root, dirs, files in os.walk('C:\'):
    for file in files:
        file_ext = os.path.splitext(root+'\'+file)[1]
        if file_ext in find_ext:
            file_paths.append(root+'\'+file)
Answered By: Allan Wind
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.