简体   繁体   English

如何在使用 Glob 和 OS 时并排打印文件夹名称和文件名称?

[英]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.运行第一个 for 循环时,它会打印目录中的文件夹名称。 When running the second, it prints all the.pdf file names that are within those folders.运行第二个时,它会打印这些文件夹中的所有.pdf 文件名。

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?我还计划将文件夹名称和相应的文件名并排打印,依此类推: ['Folder', 'File'] ['Folder', 'File'] 等等...我该怎么做做这个?

Many thanks for any help.非常感谢您的帮助。

The reason you are printing the folder is because you have two for loops.您打印文件夹的原因是因为您有两个 for 循环。 In the first loop for folder in d: you are printing the folder variable.for folder in d:您正在打印文件夹变量。 In the second for loop for files in x: you are printing the files within the folder.for files in x:的第二个 for 循环中,您正在打印文件夹中的文件。 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}')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从文件夹中打印多个随机文件名? - How can I print several random file names from a folder? 如何使用 python glob.glob() 打印子目录中的文件名 - How to print the file names in subdirectories with python glob.glob() 如何遍历文件名并使用 pathlib.glob() 打印出相应的文件名 - How to iterate through file names and print out the corresponding file names with pathlib.glob() os.walk() 不打印文件和文件夹名称 - os.walk() does not print out file and folder names Pyhton2.7.10:使用os.listdir()打印文件夹中的文件名,但要注意shell - Pyhton2.7.10:Using os.listdir() to print file names in a folder,but get noting on shell 没有使用split()和glob.glob()的输出匹配文件名 - No output matching file names using split() and glob.glob() 如何对数据集的文件名进行排序,我使用 glob.glob('path/*.png') - How do I sort the filenames for a dataset, I got the names using glob.glob('path/*.png') 使用pycparser在C文件中打印所有常量时,如何打印常量名称? - How do I print out the constant names when printing all the constants in a C file using pycparser? 如何使用 python 按字母顺序排列文件夹名称列表 - How can I order a list of folder names alphabetically using python 如何在python中并排打印两个计数器? - How can I print two counter side by side in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM