[Python] How to use python to extract files from folder base on the first 7 digits file name

Discussão em 'Python' iniciado por Stack, Agosto 3, 2025.

  1. Stack

    Stack Membro Participativo

    I am still a new learner in writing python script. I have a question here:

    I have a "folder" which contain multiple sub folders where I wish to extract PDF files base on the same first 7 digits file name in these sub folders (eg File name:AB12345_J,AB12345_K) and move these files to another new folder that I created as "Duplicate Folder". But I got a error message shown below:

    Traceback (most recent call last)
    AttributeError
    Cell In[3], line 19
    16 break
    18 if not if_dupl:
    ---> 19 duplicateFiles.append([file_x])
    21 #state the output folder
    22 Output_dir = Path('Duplicate')

    AttributeError: 'set' object has no attribute 'append'


    This is my python script:

    # Importing Libraries
    import os
    from pathlib import Path
    from filecmp import cmp

    # list of doc
    DATA_DIR = Path("folder")
    files = sorted(os.listdir(DATA_DIR))

    # list same content
    pdf_files = list(DATA_DIR.glob("\*.pdf"))
    duplicateFiles = set(\[file.name\[:6\] for file in pdf_files\])

    # compare the documents
    for file_x in files:

    if_dupl = False

    for class_ in duplicateFiles:
    # Comparing files()
    class_[6]
    if_dupl = cmp(
    DATA_DIR / file_x,
    DATA_DIR / class_[6],
    shallow=False )

    if if_dupl:
    class_.append(file_x)
    break

    if not if_dupl:
    duplicateFiles.append([file_x])

    #state the output folder
    Output_dir = Path("Duplicate Folder")

    #save to output
    with open(Output_dir,'wb') as outputfle:
    out_file.write(source_file.read())

    Continue reading...

Compartilhe esta Página