在Python中打开列表(或其他对象)中的文件(如果存在)

2024-04-25 22:27:02 发布

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

假设我有一个biiig花园,我是一个花痴,我每月都有一个csv文件的文件夹,在那里我可以跟踪我拥有的不同种类的花,以及它们在各个文件中的编号。不是每个月都开花,所以如果我要列出我所有的花文件,它可能看起来像这样:

['Roses','Lilies','Tulips','Cornflowers','Sunflowers','Hydrangea','Daisies','Dahlias','Primroses','Hibiscus']

等等(还有更多的实际文件),但是三月的文件夹可能是这样的:

['Tulips','Primroses']

六月的文件夹可能如下所示:

['Roses','Primroses','Daisies','Dahlias','Hibiscus']

现在,我每个月都对这些文件进行相同的分析,因为我想看看我的花是如何生长的,我有哪些不同的颜色,等等。但我不想每个月都要重做整个文件打开块,以适应我特定文件夹中的花文件子集-特别是因为我有30多个文件。你知道吗

那么,有没有一种简单有效的方法告诉Python“看,这是我想从中加载数据的文件名池,选择文件夹中的内容并加载它”,而不必让它创建任何不存在的文件,也不必编写30多条load语句?你知道吗

我真的很感激任何帮助!你知道吗


Tags: 文件csv文件夹编号花园种类开花roses
1条回答
网友
1楼 · 发布于 2024-04-25 22:27:02

最简单的方法是使用os.listdir(directory)列出每月目录的内容,并检查花名是否在可接受的名称列表中:

import os
path = '/path/to/the/flower/directory'
flowers = ['Roses','Lilies','Tulips','Cornflowers','Sunflowers','Hydrangea','Daisies','Dahlias','Primroses','Hibiscus']

for file in os.listdir(path):
    if file in flowers: # if the file name is in `flowers`
       with open(path + file, 'r') as flower_file:
       # do your analysis on the contents

不过,文件名需要与flowers中的字符串完全匹配。我猜文件名更像是hydrangea.csv,所以您可能需要做一些额外的过滤,例如

flowers = ['roses','lilies','tulips','cornflowers']

for file in os.listdir(path):
    # file has extension .csv and the file name minus the last 4 chars is in `flowers`
    if file.endswith(".csv") and file[0:-4] in flowers:
        with open(path + file, 'r') as flower_file:
        # do your analysis on the contents

如果您有按日期(或任何其他分组)组织的花卉文件夹,例如:

/home/flower_data/
                  2018-04/
                  2018-05/
                  2018-06/

您可以从顶级path目录执行以下操作:

path = '/home/flower_data'
# for every item in the directory
for subf in os.scandir(path):
    # if the item is a directory
    if subf.is_dir():
        # for every file in path/subfolder
        for file in os.listdir( subf.path ):
            if file.endswith('.csv') and file[0:-4] in flowers: 
               # print out the full path to the file and the file name 
               fullname = os.path.join(subf.path, file)
               print('Now looking at ' + fullname)
               with open(fullname, 'r') as flower_file:
                   # analyse away!

相关问题 更多 >