Python 忽略空文件
我们准备了一个Python脚本(Python 2.7)来制作直方图。
这个脚本叫做 histogram.py
#!/usr/bin/env python
import sys
import numpy as np
import matplotlib as mpl
import matplotlib.mlab as mlab
mpl.use('Agg')
import matplotlib.pyplot as plt
sys.argv[1] # Define input name
sys.argv[2] # Define output name
sys.argv[3] # Define title
# Open the file name called "input_file"
input_file=sys.argv[1]
inp = open (input_file,"r")
lines = inp.readlines()
if len(lines) >= 20:
x = []
#numpoints = []
for line in lines:
# if int(line) > -10000: # Activate this line if you would like to filter any date (filter out values smaller than -10000 here)
x.append(float(line))
# the histogram of the data
n, bins, patches = plt.hist(x, 50, normed=False, facecolor='gray')
plt.xlabel('Differences')
numpoints = len(lines)
plt.ylabel('Frequency ( n =' + str(numpoints) + ' ) ' )
title=sys.argv[3]
plt.title(title)
plt.grid(True)
save_file=sys.argv[2]
plt.savefig(save_file+".png")
plt.clf()
inp.close()
示例:输入数据
1
2
3
这个脚本会做以下事情
python histogram.py input ${output_file_name}.png ${title_name}
我们添加了一行代码 "if len(lines) >= 20:",这样如果数据点少于20个,就不会生成图表。
但是,如果文件是空的,这个Python脚本就会卡住。
我们添加了一行bash命令,在运行 "python histogram.py input ${output_file_name}.png ${title_name}" 之前,先删除任何空文件。
find . -size 0 -delete
出于某些原因,这行代码在小规模测试中总是能正常工作,但在实际生产中经过几次循环后就不行了。所以我们希望能让 "histogram.py" 在可能的情况下忽略任何空文件。
我们搜索后只找到这个链接,但似乎并没有太大帮助 :(
有没有人能提供一些建议?谢谢!
2 个回答
-1
在开始之前,先检查一下这个文件是否存在,并且确认它不是空的。
import os
def emptyfile(filepath):
return ((os.path.isfile(filepath) > 0) and (os.path.getsize(filepath) > 0))
2
检查一下 input_file
文件是否为空,可以用这个方法 os.path.getsize(input_file) > 0
。
你需要提供文件的完整路径,我想你应该已经有了。如果文件不存在或者无法访问,这个方法会报错,所以你可能需要考虑处理这些情况。
这段代码可以正常工作,但会忽略空文件:
#!/usr/bin/env python
import sys
import numpy as np
import matplotlib as mpl
import matplotlib.mlab as mlab
import os
mpl.use('Agg')
import matplotlib.pyplot as plt
sys.argv[1] # Define input name
sys.argv[2] # Define output name
sys.argv[3] # Define title
input_file=sys.argv[1]
# Open the file name called "input_file"
if os.path.getsize(input_file) > 0:
inp = open (input_file,"r")
lines = inp.readlines()
if len(lines) >= 20:
x = []
#numpoints = []
for line in lines:
# if int(line) > -10000: # Activate this line if you would like to filter any date (filter out values smaller than -10000 here)
x.append(float(line))
# the histogram of the data
n, bins, patches = plt.hist(x, 50, normed=False, facecolor='gray')
plt.xlabel('Differences')
numpoints = len(lines)
plt.ylabel('Frequency ( n =' + str(numpoints) + ' ) ' )
title=sys.argv[3]
plt.title(title)
plt.grid(True)
save_file=sys.argv[2]
plt.savefig(save_file+".png")
plt.clf()
inp.close()
else:
print "Empty file"
~$ python test.py empty.txt foo bar
Empty file