简体   繁体   English

如何遍历文件名并使用 pathlib.glob() 打印出相应的文件名

[英]How to iterate through file names and print out the corresponding file names with pathlib.glob()

My Directory looks like this: My Directory如下所示:

P1_SAMPLE.csv
P5_SAMPLE.csv
P7_SAMPLE.csv
P10_SAMPLE.csv

How do I iterate through files in this directory using pathlib.glob() if I want to print out the corresponding file names?如果我想打印出相应的文件名,如何使用 pathlib.glob() 遍历该目录中的文件?

My code looks like this at the moment:我的代码现在看起来像这样:

from pathlib import Path

file_path = r'C:\Users\HP\Desktop\My Directory'

for fle in Path(file_path).glob('P*_SAMPLE.csv'):
    print()  # What should the code here be?

I want my output to print this out:我希望我的 output 打印出来:

P1_sam
P5_sam
P7_sam
P10_sam

Many thanks in advance!提前谢谢了!

from pathlib import Path

file_path = r'C:\Users\HP\Desktop\My Directory'

for fle in Path(file_path).glob('P*_SAMPLE.csv'):
    first = fle.name.split('_')[0]
    second = fle.name.split('_')[1]
    print("{}_{}".format(first, second[:3].lower()))

Output: Output:

P10_sam
P1_sam
P4_sam
P5_sam

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

相关问题 当文件共享非常相似的名称时如何使用 pathlib.glob() 遍历文件 - How to iterate through files using pathlib.glob() when files share very similar names 当文件名具有不同长度的数字时,如何使用 pathlib.glob() 遍历文件 - How to iterate through files using pathlib.glob() when files names have digits of different length 如何验证 pathlib.glob 的结果? - How to validate the results of pathlib.glob? 如何使用 python glob.glob() 打印子目录中的文件名 - How to print the file names in subdirectories with python glob.glob() 我如何遍历目录,打印出文件名及其大小,并使打印输出看起来干净? - How do i iterate through a directory, and print out the file names and their sizes and make the printout clean looking? 如何在使用 Glob 和 OS 时并排打印文件夹名称和文件名称? - How, when using Glob and OS, can I print Folder names and File names side by side? Python glob匹配文件名? - Python glob matching file names? 如何遍历文件路径名列表并删除每个路径名? - How to iterate through a list of file path names and delete each one? 如何从另一个文件遍历 function 名称并调用它 function - How to iterate through function names from another file and call that function 通过使用glob排除某些目录来列出文件名 - List out file names by excluding some directories using glob
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM