Search code examples
pythonglobpathlib

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


My Directory looks like this:

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?

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:

P1_sam
P5_sam
P7_sam
P10_sam

Many thanks in advance!


Solution

  • 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 :

    P10_sam
    P1_sam
    P4_sam
    P5_sam