ValueError: too many values to unpack while parsing the txt

I have a small txt file, where I need to replace the multiple spaces with single tab on the lines that begin with specific keyword, so for that firstly I replace the multiple spaces with single one, that will be then replaced by tab My script:

input_file=open('file.txt', "rw")
for i, line in input_file:
    if line.startswith('City'):
        while '  ' in line:
            line = line.replace('  ', ' ')
        input_file.write(line)
input_file.close   

and I have this error:

ValueError                                Traceback (most recent call last)
<ipython-input-26-dfd976cfc18d> in <module>()
      1 input_file=open('file.txt', "rw")
----> 2 for i, line in input_file:
      3     if line.startswith('City'):
      4         while '  ' in line:
      5             line = line.replace('  ', ' ')

ValueError: too many values to unpack

Why it could happen?

Answers


If you really need i, which is a number (starting from 0 if start keyword argument is not defined) that increments on each iteration and generated by enumerate :

Try adding enumerate():

for i, line in enumerate(input_file):

If you don't, just use:

for line in input_file:

Regarding "double white-space deletion", there is no need to use while. Just use if and replace:

if '  ' in line:
    line = line.replace('  ', ' ')
input_file.write(line)

Regarding open(), you can avoid closing the opened file by using with statement.

This has the advantage that the file is properly closed after its suite finishes

with open('file.txt', "rw") as input_file:
    for line in input_file:
        if line.startswith('City'):
            if '  ' in line:
                line = line.replace('  ', ' ')
            input_file.write(line)

See the last example of this section https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects


Change open() mode from "rw" to "r+", to avoid the following error:

IOError: [Errno 9] Bad file descriptor


Need Your Help

call same function on different non-related objects?

.net function object c++-cli

I have a set of objects, all of a different type, lets say

Spring MVC form:options tag not wiring into my objects Id?

java spring forms spring-mvc jstl

I am trying to display my command objects collection field inside a list box. Inside said collection is a field, id and name. I want use the id as the html option value and the name as the option t...