从路径选择文件

2024-07-04 05:16:43 发布

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

我有特定路径的文件,需要根据namefile逐个选择(yyyymmdd.faifb1p16m2.nc),其中yyyy是年,mm是月,dd是日期。我编写了这样的代码:

results=[]
base_dir = 'C:/DATA2013'
os.chdir(base_dir) 
files = os.listdir('C:/DATA2013')
for f in files:
    results += [each for each in os.listdir('C:/DATA2013')
    if each.endswith('.faifb1p16m2.nc')] 

如果我只选择1月份的文件,然后选择2月份的文件,那么接下来该怎么办,依此类推。非常感谢。你知道吗


Tags: 文件in路径forbaseosdirfiles
3条回答

要验证文件名,可以使用^{} method

#!/usr/bin/env python
import os
from datetime import datetime
from glob import glob

suffix = '.faifb1p16m2.nc'

def parse_date(path):
    try:
        return datetime.strptime(os.path.basename(path), '%Y%m%d' + suffix)
    except ValueError:
        return None # failed to parse


paths_by_month = [[] for _ in range(12 + 1)]
for path in glob(r'C:\DATA2013\*' + suffix): # for each nc-file in the directory
    date = parse_date(path)
    paths_by_month[date and date.month or 0].append(path)

print(paths_by_month[2]) # February paths
print(paths_by_month[0]) # paths with unrecognized date

你可以做:

x = [i for i in results if i[4:6] == '01']

它将列出一月份的所有文件名。 假设您的所有文件的格式与您在问题中描述的相同。你知道吗

两个正则表达式:

  1. \d{4}(?:\d?|\d{2})(?:\d?|\d{2})\.faifb1p16m2\.nc
  2. \d{8}\.faifb1p16m2\.nc

样本数据:

  1. 20140131.faifb1p16m2.nc
  2. 2014131.faifb1p16m2.nc
  3. 201412.faifb1p16m2.nc
  4. 201411.faifb1p16m2.nc
  5. 20141212.faifb1p16m2.nc
  6. 2014121.faifb1p16m2.nc
  7. 201411.faifb1p16m2.nc

第一个正则表达式将匹配所有7个条目。第二个正则表达式将只匹配1和5。我可能把正则表达式弄得比我需要的复杂多了。你知道吗

您将需要第二个正则表达式,但我只是将第一个列为示例。

from glob import glob
import re

re1 = r'\d{4}(?:\d?|\d{2})(?:\d?|\d{2})\.faifb1p16m2\.nc'
re2 = r'\d{8}\.faifb1p16m2\.nc'

l = [f for f in glob('*.faifb1p16m2.nc') if re.search(re1, f)]
m = [f for f in glob('*.faifb1p16m2.nc') if re.search(re2, f)]

print l
print
print m
#Then, suppose you want to filter and select everything with '12' in the list m
print filter(lambda x: x[4:6] == '12', m)

作为another similar solution shows,您可以放弃glob操作系统列表目录(),所以:

l = [f for f in glob('*.faifb1p16m2.nc') if re.search(re1, f)]`

变成:

l = [f for f in os.listdir() if re.search(re1, f)]

然后剩下的代码就很棒了。使用glob的一个好处是,您可以使用iglob,它与glob类似,但作为迭代器,在遍历包含大量文件的目录时可以提高性能。你知道吗

还有一件事,下面是另一篇stackoverflow文章,概述了python's infamous lambda feature。它通常用于函数mapreducefilter,等等。你知道吗

相关问题 更多 >

    热门问题