python - 带条件保存文件名

标签 python file input

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

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

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

我想保存具有以下内容的数据文件的文件名(或文件名的一部分,如果这是一个简单的修复,否则我可以在之后sed该文件)第四个数字([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,但我不知道它指的是什么。

最佳答案

我最终使用了

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()

关于python - 带条件保存文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31461506/

相关文章:

mysql - SQL : How to use SELECT results as function input parameters

python - 如何让 googlemaps python 库检测 SSL 证书?

python - 如何根据模糊条件从Numpy数组中选择值?

python - 使用 Expect 在远程机器上运行本地 Python 脚本

scala - 使用 Akka Streams、Scala 异步读取多个文件

c - 我尝试分解我的功能,但我不确定我是否做对了

Python遍历目录并打开txt文件

JavaScript - 从数组中的多个输入获取值

java - 断言用户输入是大写字母

python - 如何使用 for 循环和 Python 中的 csv 库遍历列?