简体   繁体   中英

How, when using Glob and OS, can I print Folder names and File names side by side?

    import os
    import glob

    d = os.listdir("Path")

    for folder in d:
     print(folder)

    x = glob.glob("Path/**/*.pdf")

    for files in x:
     print(files)

When running the first for loop, it prints the folder names within the directory. When running the second, it prints all the.pdf file names that are within those folders.

However, when printing the file names, it also prints the directory, before the file name. How can I only print the file name and not the directory?

I also plan to have both the folder names and the corresponding file name printed side by side, and so on: ['Folder', 'File'] ['Folder', 'File'] and so on... How can I do this?

Many thanks for any help.

The reason you are printing the folder is because you have two for loops. In the first loop for folder in d: you are printing the folder variable. In the second for loop for files in x: you are printing the files within the folder. To do what you want, get the folders within the path, then loop through each folder and find the files, you can then print the folder and filename on the same line as shown below:

import os
import glob

d = os.listdir("Path")

for folder in d:
    x = glob.glob("Path/**/*.pdf")
    for file in x:
        print(f'{folder}\t{file}')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM