【问题标题】:Saving Filenames with Condition保存有条件的文件名
【发布时间】:2015-07-16 18:07:59
【问题描述】:

我正在尝试保存满足特定条件的文件的名称。 我认为最简单的方法是编写一个简短的 Python 程序来导入和读取文件,检查是否满足条件,然后(假设满足)保存文件的名称。

我的数据文件只有两列四行,如下所示:

 a:    5
 b:    5
 c:    6
 de:    7

我想保存具有第 4 个数字([ 3:1]) 大于 8。我尝试使用numpy 导入文件,但它说它无法导入第一列中的字母。

我正在考虑尝试执行此操作的另一种方法是从命令行执行类似于 cat *.dat >> something.txt 的操作,但我不知道如何执行此操作。

我尝试编写的代码是:

import fileinput
import glob
import numpy as np

#Filter to find value > 8

#Globbing value datafiles
file_list = glob.glob("/path/to/*.dat")

#Creating output file containing
f = open('list.txt', 'w')

#Looping over files
for file in file_list:
        #For each file in the directory, isolating the filename
        filename = file.split('/')[-1]
        #Opening the files, checking if value is greater than 8
        a = np.loadtxt("file", delimiter=' ', usecols=1)
        if a[3:0] > 8:
                print >> f,  filename
f.close()

当我这样做时,我收到一条错误消息,上面写着 TypeError: 'int' object is not iterable,但我不知道它指的是什么。

【问题讨论】:

标签: python file input


【解决方案1】:

我最终使用了

import fileinput
import glob
import numpy as np

#Filter to find value > 8

#Globbing datafiles
file_list =  glob.glob("/path/to/*.dat")

 #Creating output file containing
 f = open('list.txt', 'w')

 #Looping over files
 for file in file_list:
        #For each file in the directory, isolating the filename
        filename = file.split('/')[-1]
        #Opening the files, checking if value is greater than 8
        a = np.genfromtxt(file)
        if a[3,1] > 8:
                f.write(filename + "\n")
f.close()

【讨论】:

    【解决方案2】:

    很难准确地说出你想要什么,但可能是这样的

    from glob import glob
    from re import findall
    fpattern = "/path/to/*.dat"
    
    def test(fname):
        with open(fname) as f:
            try:
               return int(findall("\d+",f.read())[3])>8
            except IndexError:
               pass
    
    matches = [fname for fname in glob(fpattern) if test(fname)]
    print matches
    

    【讨论】:

    • 当我尝试这个时,我得到一个错误提示:TypeError: 'module' object is not callable
    • 你做了from glob import glob 吗? (我也有一个小错字...现在已修复)...该错误在哪一行?
    猜你喜欢
    • 1970-01-01
    • 2010-11-15
    • 1970-01-01
    • 1970-01-01
    • 2011-08-16
    • 1970-01-01
    • 1970-01-01
    • 2012-08-26
    • 1970-01-01
    相关资源
    最近更新 更多