在扩展名和大小上过滤os.walk文件

问题描述 投票:0回答:2

我有一个小例程,它读取目录中的文件并按扩展名(.csv)过滤它们。我还想按文件大小过滤这些文件。例如,小于100字节的文件,因此我只有扩展名为(.csv)且大于100字节的文件。

for root, dirs, files in os.walk(CSVDIR):
    for file in files:
        if file.endswith('.csv'):
            fullname = os.path.join(root, file).replace('/', '/')
            filename = os.path.splitext(os.path.basename(fullname))[0]

            print (file)

我可以用吗? if os.stat().st_size >3

python python-3.x
2个回答
0
投票

你可以使用我喜欢的os.path.getsize。你也不需要在树上寻找这些文件:你可以使用带递归的glob:

import os
import glob
csvfiles = [file for file in glob.iglob('CSVDIR/**/*.csv',recursive=True) if os.path.getsize(file) > 100]

无论何时使用glob.glob或glob.iglob进行递归,都需要像文件路径搜索模式中那样包含**。我在这里使用了iglob,因为我喜欢它返回迭代器的方式,但是你可以使用glob来返回一个列表 - 如果你想将glob调用与列表理解隔离以检查它的元素,你可能想要这样做。


0
投票

@ Billiam谢谢你的回答也有效但我现在选择了不同的解决方案。

@Aran-Fey为何如此咄咄逼人。?我认为他们也想帮助启动程序员而不是给出批评意见。幸运的是,还有其他人可以理解一个愚蠢的问题。

for root, dirs, files in os.walk(CSVDIR):
            for file in files:
                S = os.path.getsize((CSVDIR)+(file))
                if S > 3:
                    if file.endswith('.csv'):
                        print (file)
                        fullname = os.path.join(root, file).replace('/', '/')
                        filename = os.path.splitext(os.path.basename(fullname))[0]

                        uri = 'file:///%s?crs=%s&delimiter=%s&xField=%s&yField=%s&decimal=%s&useHeader=no&' % (fullname, 'EPSG:4326', ';', 'Field_8', 'Field_9', ',')
                        layer = QgsVectorLayer(uri, 'my_layer', 'delimitedtext')
                        QgsVectorFileWriter.writeAsVectorFormat(layer, DESTDIR + '/' + filename + '.shp', 'CP1250', layer.crs(), 'ESRI Shapefile')
© www.soinside.com 2019 - 2024. All rights reserved.