我有一个打开文件的代码,计算中值并将该值写入单独的文件。一些文件可能是空的,因此我编写了以下循环来检查文件是否为空,如果是,请跳过它,增加计数并返回循环。它对找到的第一个空文件执行预期的操作,但对第二个不执行预期的操作。循环在下面
t = 15.2 while t>=11.4: if os.stat(r'C:\Users\Khary\Documents\bin%.2f.txt'%t ).st_size > 0: print("All good") F= r'C:\Users\Documents\bin%.2f.txt'%t print(t) F= np.loadtxt(F,skiprows=0) LogMass = F[:,0] LogRed = F[:,1] value = np.median(LogMass) filesave(*find_nearest(LogMass,LogRed)) t -=0.2 else: t -=0.2 print("empty file")
输出如下
All good 15.2 All good 15.0 All good 14.8 All good 14.600000000000001 All good 14.400000000000002 All good 14.200000000000003 All good 14.000000000000004 All good 13.800000000000004 All good 13.600000000000005 All good 13.400000000000006 empty file All good 13.000000000000007 Traceback (most recent call last): File "C:\Users\Documents\Codes\Calculate Bin Median.py", line 35, in <module> LogMass = F[:,0] IndexError: too many indices
第二个问题是,t以某种方式从小数点后一位上升到15位,而最后一位似乎增加了小数位?感谢您提供的所有帮助
编辑 该错误IndexError: too many indices 似乎仅适用于仅使用一行示例的文件…
IndexError: too many indices
12.9982324 0.004321374
如果我添加第二行,我不再收到错误,有人可以解释这是为什么吗?谢谢
编辑
我尝试了一个小实验,如果数组只有一行,似乎numpy不喜欢提取列。
In [8]: x = np.array([1,3]) In [9]: y=x[:,0] --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-9-50e27cf81d21> in <module>() ----> 1 y=x[:,0] IndexError: too many indices In [10]: y=x[:,0].shape --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-10-e8108cf30e9a> in <module>() ----> 1 y=x[:,0].shape IndexError: too many indices In [11]:
要处理单行文件的情况,请将ndmin参数添加到np.loadtxt(查看其文档):
np.loadtxt('test.npy',ndmin=2) # array([[ 1., 2.]])
您应该使用try / except块。就像是:
t = 15.2 while t >= 11.4: F= r'C:\Users\Documents\bin%.2f.txt'%t try: F = np.loadtxt(F,skiprows=0) LogMass = F[:,0] LogRed = F[:,1] value = np.median(LogMass) filesave(*find_nearest(LogMass,LogRed)) except IndexError: print("bad file: {}".format(F)) else: print("file worked!") finally: t -=0.2
有关异常处理的更多详细信息,请参考官方教程。
随着最后一位的问题是由于浮动是如何工作的,他们不能代表base10号码完全相同。这可能会带来有趣的事情,例如:
In [13]: .3 * 3 - .9 Out[13]: -1.1102230246251565e-16