以特定模式读取数据组

2024-10-01 11:23:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我在目录中有如下数据

 IU.WRT.00.MTR.1999.081.081015.txt
 IU.WRT.00.MTS.2007.229.022240.txt
 IU.WRT.00.MTR.2007.229.022240.txt
 IU.WRT.00.MTT.1999.081.081015.txt
 IU.WRT.00.MTS.1999.081.081015.txt
 IU.WRT.00.MTT.2007.229.022240.txt

我想读数据组

首先,我想读取3个模式相似的文件(不同于R、S、T)

IU.WRT.00.MTR.1999.081.081015.txt
IU.WRT.00.MTS.1999.081.081015.txt
IU.WRT.00.MTT.1999.081.081015.txt

想对它进行一些操作吗

然后我想读取数据

IU.WRT.00.MTT.2007.229.022240.txt
IU.WRT.00.MTS.2007.229.022240.txt
IU.WRT.00.MTR.2007.229.022240.txt 

并希望在其上应用类似的操作

同样,我想继续处理数百万个数据集

我尝试了示例脚本

import os
import glob
import matplotlib.pyplot as plt
from collections import defaultdict

def groupfiles(pattern):
    files = glob.glob(pattern)
    filedict = defaultdict(list)
    for file in files:
        parts = file.split(".")
        filedict[".".join([parts[5], parts[6], parts[7]])].append(file)
    for filegroup in filedict.values():
        yield filegroup
 
for relatedfiles in groupfiles('*.txt'):
    print(relatedfiles)

    for filename in relatedfiles:
        print(filename)

    

但是它会一个接一个地读取文件,但是我需要一次读取3个文件。我希望专家可以帮助我。提前感谢


Tags: 文件数据inimporttxtforglobfile
1条回答
网友
1楼 · 发布于 2024-10-01 11:23:20

使用适当的模式获取文件

files_1999 = glob.glob('IU.WRT.00.MT[RST].1999.081.081015.txt')

概括地说

years = set(file.split('.')[4] for file in glob.glob('*.txt'))
file_group = {}

for year in years:
    pattern = f'IU.WRT.00.MT[RST].{year}*.txt'
    file_group[year] = glob.glob(pattern)

输出

{
   "2007":[
      "IU.WRT.00.MTS.2007.229.022240.txt",
      "IU.WRT.00.MTR.2007.229.022240.txt",
      "IU.WRT.00.MTT.2007.229.022240.txt"
   ],
   "1999":[
      "IU.WRT.00.MTS.1999.081.081015.txt",
      "IU.WRT.00.MTR.1999.081.081015.txt",
      "IU.WRT.00.MTT.1999.081.081015.txt"
   ]
}

相关问题 更多 >