我试图保存满足特定条件的文件名称。我认为最简单的方法是编写一个简短的Python程序来导入和读取文件,检查是否满足条件,然后(假设满足条件)保存文件名。
我的数据文件只有两列四行,像这样:
a: 5
b: 5
c: 6
de: 7
我想保存第4个数字([3:1])大于8的数据文件的文件名称(或文件名称的一部分,如果这是一个简单的修复,否则我可以稍后将文件sed
)。我试着用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()
很难确切地说出你想要什么,但也许像这样
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