[英]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.