python - 在 Python 中拆分字符串时出现问题

标签 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

最佳答案

当线被分割一次时,它给出一个列表。当您使用 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)

关于python - 在 Python 中拆分字符串时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27908534/

相关文章:

python - 如何在 pyomo 模型中提取索引变量信息并构建 Pandas Dataframe

python - Scipy 在 Julia 中使用 PyCall

python - 计算数据框中特定值的出现次数,其中所有可能的值都由列表定义

c++ - C 标记化多项式系数

python - 升级 pip : UnicodeDecodeError: 'utf-8' codec can't decode byte 时出错

java - 非空字符串中的空字符串

python - 如何在 Python 中将二维数组的字符串值转换为整数值?

c++ - 不直接使用字符串时的CreateProcess @Unhandled异常

c# - url 字符串中的斜杠 (c#)

python - 更改 Python 语音识别中的语言