How to read space separated file in python?

Joe Strout joe at strout.net
Fri Nov 21 11:13:23 EST 2008


On Nov 21, 2008, at 9:00 AM, Steve Holden wrote:

> Joe Strout wrote:
>> On Nov 21, 2008, at 2:08 AM, Steven D'Aprano wrote:
>>
>>>   a, b = line.split()
>>
>> Note that in a case like this, you may want to consider using  
>> partition
>> instead of split:
>>
>>  a, sep, b = line.partition(' ')
>>
>> This way, if there happens to be more than one space (for example,
>> because the Unicode character you're mapping to happens to be a  
>> space),
>> it'll still work.  It also better encodes the intention, which is to
>> split only on the first space in the line, rather than on every  
>> space.
>>
> In the special case of the None first argument (the default for the
> str.split() method) runs of whitespace *are* treated as single
> delimiters. So line.split() is not the same as line.split(' ').

Right -- so using split() gives you the wrong answer for two different  
reasons.  Try these:

 >>> line = "1 x"
 >>> a, b = line.split()   # b == "x", which is correct

 >>> line = "2  "
 >>> a, b = line.split()   # correct answer would be b == " "
ValueError: need more than 1 value to unpack

 >>> line = "3 x and here is some extra stuff"
 >>> a, b = line.split()   # correct answer would be b == "x and here  
is some extra stuff"
ValueError: too many values to unpack

Partition handles these cases correctly (at least, within the OP's  
specification that the value of "b" should be whatever comes after the  
first space).

Cheers,
- Joe




More information about the Python-list mailing list