Gravity000
Gravity000

Reputation: 1

Split txt file with open spaces

I'm trying to split a text file in Python but I get the following error:

ValueError: need more than 1 value to unpack

My code:

for line in lines:
    x, y, e, r, t=line.split()
    return x, y, e, r, t

the format of the text file is

x y e r t

but some lines are missing numbers or letters, for example

 x   e r t
 x y   r t

So I guess that is why I get the error, but I can't find a way to resolve it. Is it possible to also count the blank spaces as a variable?

Upvotes: 0

Views: 478

Answers (3)

dimo414
dimo414

Reputation: 48864

This answer assumes the lines are missing fields, @Poke's answer assumes the fields have been replaced with a space (leaving three spaces between the other fields).

The docs on .split() tell you everything you need to know.

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].

So simply specify sep=' ' in your call to .split(), i.e.:

line.split(' ')

So that the separator is exactly one space.

>>> x, y, e, r, t = "x y e r t".split(' ')
>>> print((x, y, e, r, t))
('x', 'y', 'e', 'r', 't')

>>> x, y, e, r, t = "x  e r t".split(' ')
>>> print((x, y, e, r, t))
('x', '', 'e', 'r', 't')

>>> x, y, e, r, t = "x y  r t".split(' ')
>>> print((x, y, e, r, t))
('x', 'y', '', 'r', 't')

Upvotes: 2

poke
poke

Reputation: 388133

>>> 'x   e r t'.replace('  ', ' _').split(' ')
['x', '_', 'e', 'r', 't']
>>> 'x y   r t'.replace('  ', ' _').split(' ')
['x', 'y', '_', 'r', 't']
>>> 'x     r t'.replace('  ', ' _').split(' ')
['x', '_', '_', 'r', 't']

And then just check for the special value '_' that signalizes a missing value.

Upvotes: 2

Anand S Kumar
Anand S Kumar

Reputation: 90979

Assuming the number of spaces between each character is only 1 , and an extra whitespace in between indicates an empty variable. I think your best bet would be to not use line.split() function , instead move over each character in the line and determine the values you need.

A code like this -

lst = []
for line in lines:
    for i in xrange(0,len(line),2):
         if line[i] == ' ':
             lst.append(' ')         # or whatever you use for empty variables
         else:
             lst.append(line[i])
   return lst

Then you can unpack the list from whereever you are calling the above function

Upvotes: 1

Related Questions