Radamand
Radamand

Reputation: 185

Problems splitting a string in Python

I'm trying to read some values from a file, but I keep getting errors when trying to split them up;
The text file looks like this:

2009-10 0:12:01
2009-12 0:06:24
2010-06 0:29:24
2012-06 0:10:29

Here's my code;

myFiles = glob.glob('./*.txt')
for fileName in myFiles:
    fileHandle = open(fileName,'r')
    print str(fileName)
    for date, value in str(fileHandle.readline()).split(' ',1):
        print "date: " + str(date)
        print "value: " + str(value)

What I want to output:

<filename>
date: 2009-10
value: 0:12:01
date: 2009-12
value: 0:06:24
date: 2010-06
value: 0:29:24
date: 2012-06
value: 0:10:29
<filename>
etc
etc...

The error I'm getting:

Traceback (most recent call last):
  File "./scratch.py", line 16, in <module>
    for date, value in str(fileHandle.readlines()).split(' ',1):
ValueError: too many values to unpack

Upvotes: 1

Views: 1509

Answers (4)

xnx
xnx

Reputation: 25570

You're not iterating over the lines in your file correctly:

    for date, value in str(fileHandle.readline()).split(' ',1):

This iterates over the two fields in the first line only: ['2009-12', '0:06:24\n']. Each field is a single string, so can't be unpacked into date, value. Why not try the more direct:

import glob

myFiles = ['input.txt']
for fileName in myFiles:
    fileHandle = open(fileName,'r')
    print str(fileName)
    for line in fileHandle:
        date, value = line.split()
        print "date: " + str(date)
        print "value: " + str(value)

input.txt
date: 2009-10
value: 0:12:01
date: 2009-12
value: 0:06:24
date: 2010-06
value: 0:29:24
date: 2012-06
value: 0:10:29

Upvotes: 1

jbihan
jbihan

Reputation: 3099

As far as I know you can't split while iterating on the lines. What you could do is read each line, then split this line and get the result:

myFiles = glob.glob('./*.txt')
for fileName in myFiles:
    fileHandle = open(fileName,'r')
    print str(fileName)
    for line in fileHandle.readlines():
        print "date: " + str(line.split(' ')[0])
        print "value: " + str(line.split(' ')[1])

Upvotes: 2

Daniel
Daniel

Reputation: 5391

A simpler approach to the problem

with open ("path to file\\test.txt","r") as f:
    for line in f:  
        date, value = line.split()
        print "date: {}".format(date)
        print "value: {}".format(value)

output:

date: 2009-10
value: 0:12:01
date: 2009-12
value: 0:06:24
date: 2010-06
value: 0:29:24
date: 2012-06
value: 0:10:29

Upvotes: 3

thefourtheye
thefourtheye

Reputation: 239693

When the line is split once, it gives a list. When you iterate the list, like the way you have done, with for, it expects it to be an iterable of items, each of which can be unpacked over two variables.

Your for statement is equivalent to this, after reading the first line

for date, value in ['2009-10', '0:12:01']:
    ...

That is why it fails with that error.

A better way to do this would be,

import glob

# Iterate the found files
for fileName in glob.glob('./*.txt'):
    # Open the file with `with` statement
    with open(fileName, "r") as fileHandle:
        print str(fileName)

        # Give date and value from each line, with generator expression
        for date, value in (line.strip().split(' ',1) for line in fileHandle):
            # Print with the template string
            print "date: {}\nvalue: {}".format(date, value)

Upvotes: 3

Related Questions