[Python] What do f, dirpath, dirname, and filenames do specifically in this code? Trying to...

Discussão em 'Python' iniciado por Stack, Junho 17, 2025.

  1. Stack

    Stack Membro Participativo

    I am a beginner and reading somebody else's code to understand what they were doing and to learn. I understand overall what their code is doing, but since I'm trying to learn too, I want to make sure I know each individual part. Would you please let me know if I'm reading this correctly?

    Below is part of their code that looks for PDFs in a specified location and counts the number of pages in those PDFs.

    rootpath = "C:\\examplefolder"

    filepaths = [join(dirpath,f) for (dirpath, dirnames, filenames) in walk(rootpath) for f in filenames]

    pdfs = []
    for f in filepaths:
    pages = 0
    if f.endswith(".pdf"):
    try:
    pages = GetPDFPageCount(f)
    except UserWarning:
    print("Unable to read file at: " + f)
    pages = 0
    except:
    print("Unknown exception with file at: " + f)
    pages = 0


    What I think I'm reading / gaps in my understanding:

    Code Interpretation
    rootpath = "C:\\examplefolder" defines the folder location as C:\\examplefolder
    filepaths = [join(dirpath,f) for (dirpath, dirnames, filenames) in walk(rootpath) for f in filenames] defines "filepaths" as ??? I don't understand the join(dirpath,f) or the for (dirpath, dirnames, filenames). It then "walks through" the entire folder location and defines this name for every f.
    pdfs = [] What does this mean? I'm not sure what a "slicer" is.
    for f in filepaths: f is a variable that represents every... file? in the specified filepaths location
    pages = 0 why do I need this? is this telling it to start the page count at 0 for each file?
    if f.endswith(".pdf"): if the file is a .pdf file...
    try: then...
    pages = GetPDFPageCount(f) defines "pages" as the integer from the earlier (not included here) "GetPDFPageCount" function for every file

    Continue reading...

Compartilhe esta Página