在Python中拆分字符串的问题

时间:2015-01-12 18:34:42

标签: python string

我试图从文件中读取一些值,但在尝试拆分它时我一直遇到错误;
文本文件如下所示:

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

这是我的代码;

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)

我想输出的内容:

<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...

我得到的错误:

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

3 个答案:

答案 0 :(得分:3)

当线被分割一次时,它会给出一个列表。当您使用for迭代列表时,就像您完成的那样,它希望它是一个可迭代的项目,每个项目都可以在两个变量上解压缩。

在阅读第一行

后,您的for语句与此相同
for date, value in ['2009-10', '0:12:01']:
    ...

这就是为什么它失败了。

更好的方法是,

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)

答案 1 :(得分:3)

解决问题的更简单方法

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)

输出:

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

答案 2 :(得分:1)

您没有正确迭代文件中的行:

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

这只迭代第一行中的两个字段:['2009-12', '0:06:24\n']。每个字段都是一个字符串,因此无法解压缩到date, value。为什么不尝试更直接:

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