我正在使用 Path().glob() 遍历目录中的文件,但它没有以正确的自然顺序进行迭代。例如。它像这样迭代:
[WindowsPath('C:/Users/HP/Desktop/P1/dataP1/SAMPLED_NORMALIZED/P1_Cor.csv'),
WindowsPath('C:/Users/HP/Desktop/P10/dataP10/SAMPLED_NORMALIZED/P10_Cor.csv'),
WindowsPath('C:/Users/HP/Desktop/P11/dataP11/SAMPLED_NORMALIZED/P11_Cor.csv'),
WindowsPath('C:/Users/HP/Desktop/P12/dataP12/SAMPLED_NORMALIZED/P12_Cor.csv'),
# ...and so on from P1 to P30
当我希望它像这样迭代时:P1、P2、P3 等等。
我尝试使用下面的代码,但它给了我一个错误:
from pathlib import Path
file_path = r'C:/Users/HP/Desktop'
files = Path(file_path).glob(file)
sorted(files, key=lambda name: int(name[10:]))
在我尝试代码时,10 只是一个微不足道的数字。
错误:
TypeError: 'WindowsPath' object is not subscriptable
最终,我想要的是遍历文件并对每个文件做一些事情:
from pathlib import Path
for i, fl in enumerate(Path(file_path).glob(file)):
# do something
我什至尝试过该库natsort
,但它没有在迭代中正确排序文件。我试过了:
from natsort import natsort_keygen, ns
natsort_key1 = natsort_keygen(key=lambda y: y.lower())
from natsort import natsort_keygen, ns
natsort_key2 = natsort_keygen(alg=ns.IGNORECASE)
上面的两个代码仍然给我 P1、P10、P11 等等。
任何帮助将不胜感激。