else statement does not return to loop

筅森魡賤 提交于 2019-12-24 15:25:56

问题


I have a code that opens a file, calculates the median value and writes that value to a separate file. Some of the files maybe empty so I wrote the following loop to check it the file is empty and if so skip it, increment the count and go back to the loop. It does what is expected for the first empty file it finds ,but not the second. The loop is below

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

The output is as follows

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

A second issue is that t somehow goes from one decimal place to 15 and the last place seems to incrementing whats with that? Thanks for any and all help

EDIT The error IndexError: too many indices only seems to apply to files with only one line example...

12.9982324  0.004321374

If I add a second line I no longer get the error can someone explain why this is? Thanks

EDIT

I tried a little experiment and it seems numpy does not like extracting a column if the array only has one row.

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]: 

回答1:


You should be using try/except blocks. Something like:

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

Please refer to the official tutorial for more details about exception handling.

The issue with the last digit is due to how floats work they can not represent base10 numbers exactly. This can lead to fun things like:

In [13]: .3 * 3 - .9
Out[13]: -1.1102230246251565e-16



回答2:


To deal with the one line file case, add the ndmin parameter to np.loadtxt (review its doc):

np.loadtxt('test.npy',ndmin=2)
# array([[ 1.,  2.]])



回答3:


With the help of a user named ajcr, found the problem was that ndim=2 should have been used in numpy.loadtxt() to insure that the array always 2 has dimensions.




回答4:


Python uses indentation to define if while and for blocks.

It doesn't look like your if else statement is fully indented from the while.

I usually use a full 'tab' keyboard key to indent instead of 'spaces'



来源:https://stackoverflow.com/questions/29191240/else-statement-does-not-return-to-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!