[Tutor] Problem Moving Python Program From WIndows to Linux

Daniel Yoo dyoo@hkn.eecs.berkeley.edu
Tue, 10 Apr 2001 02:39:55 -0700 (PDT)


On Tue, 10 Apr 2001, Jethro Cramp wrote:

> The error I get when I run this code is:
> 
> Traceback (most recent call last):
>    File "<stdin>", line 1, in ?
>    File "/usr/lib/python2.0/rk/rkcalc.py", line 172, in Get_Materials_List
>      mat, mass = map(string.strip, string.split(material, "="))
> ValueError: unpack list of wrong size
> 
> Are the tab stops being treated differently in Linux from Windows?


> Also when I open a file in idle that I wrote under windows there is a 
> "\r" at the end of each line. Is this some kind of windows specific end 
> of line character.


About the tab stops: not that I can tell.  However, you're right about the
"\r" stuff: it's the carriage return character that Windows/DOS systems
use in conjunction with "\n".



>  >>> file = open(rkpaths.material_specs, "r")
>  >>> x = file.readlines()
> for entry in x:
> 	print entry
> 
> # This file contains a list of materials and their mass in MT/m3\r
> 
> \r


Ah, here's something.  If your first line contains a '\r', it's still a
line, so the command

    x,y = string.split(entry,"=")

will try doing the string split across this line --- that's what's causing
the problem when we tuple-unpack later on.  Same sort of thing happens if
there are blank lines in your file.

One way to fix this is to tell your loop to "skip over" blank lines:

###
for entry in x:
    if string.strip(entry) == "": continue
    # ... the rest is the same
###

"continue" will tell Python to skip this element, and consider the next
element in x.  For example:


###
>>> for x in range(10):
...     if x % 2 == 0: continue
...     print x
...
1
3
5
7
9 
###

Another, more robust way to fix this problem is to use exception
handling.  Can someone give a good explanation about this?




> Notice all the '\r' entries.

Use string.strip() to get rid of that trailing whitespace stuff.  strip()
will help you clean up a string from both the left and right side.  It's
probably better to do it after unpacking the tuple, just to get rid of all
that whitespace at once.

Hope this helps!