如何遍历文件名并使用 pathlib.glob() 打印出相应的文件名
How to iterate through file names and print out the corresponding file names with pathlib.glob()
My Directory
看起来像这样:
P1_SAMPLE.csv
P5_SAMPLE.csv
P7_SAMPLE.csv
P10_SAMPLE.csv
如果我想打印出相应的文件名,如何使用 pathlib.glob() 遍历此目录中的文件?
目前我的代码如下所示:
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?
我希望我的输出打印出来:
P1_sam
P5_sam
P7_sam
P10_sam
非常感谢!
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
My Directory
看起来像这样:
P1_SAMPLE.csv
P5_SAMPLE.csv
P7_SAMPLE.csv
P10_SAMPLE.csv
如果我想打印出相应的文件名,如何使用 pathlib.glob() 遍历此目录中的文件?
目前我的代码如下所示:
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?
我希望我的输出打印出来:
P1_sam
P5_sam
P7_sam
P10_sam
非常感谢!
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