file operations.

Terry Reedy tjreedy at udel.edu
Thu Jul 24 21:33:17 EDT 2008



aditya shukla wrote:
> Guys thanks for your previous help .I have a doubt again
> 
> My text file is :-
> 
> 0\9\10\11|0.50|c:\windows\apppatch/AcLayers.dll
...
> 
> now this is what happens
> 
>  >>> x=open("c:\\test2.txt","rb")
>  >>> x.readline()
> 
> '\n' ---? i am not able to understand why  is  new line character 
> returned here

Either because your text file starts with a blank line or because 
.readline does not work when you open in binary mode.  In any case, you 
should probably change 'rb' to 'r'.

> 
>  >>> l =x.readline()
>  >>> print l
> 
> 
> Also , because of this i am not able to extract the floating point 
> values ie 0.50,0.50,0.66 respectively
> cause when i use the proposed solution given earlier
> 
> data=[]
> for line in x:
>    line=line.split("|")
>    data.append(float(line[-2])) --> i am trying to get the floating 
> point values from the back
>   
> i receive this error message
> 
> Traceback (most recent call last):
>   File "<pyshell#71>", line 3, in <module>
>     d.append(float(line[-2]))
> IndexError: list index out of range

If you have a blank line, splitting returns a list of length 0 or 1, so 
there is no -2 element.  Add something like
   if len(line) < 2: raise SomeError(message)
after the split.  If you should always have 3 parts, check '==3' and 
index to line[1].

tjr




More information about the Python-list mailing list