python - .split() 和 .append 来自 .txt 文件的信息作为元组到新列表

标签 python list split append tuples

我正在尝试使用 while 循环逐行读取 .txt 文件,在逗号交叉处分割每一行,调用一个函数将每行的“日期”一侧返回到列表,然后 append “任务”一侧添加到列表中的日期时间。

.txt 文件中的示例行:“tutorial Signons,28/02/2014”

结果应如下所示:(datetime.datetime(2014, 2, 28, 0, 0), 'tutorial Signons')

我现在的代码返回的是: ['t'、'u'、't'、'o'、'r'、'i'、'a'、'l'、' '、's'、'i'、'g'、'n ', 'o', 'n', 's', ',', '2', '8', '/', '0', '2', '/', '2', '0', '1', '4', '\n']

日期时间函数:

def as_datetime(date_string):
    try:
        return datetime.datetime.strptime(date_string, DATE_FORMAT)
    except ValueError:
        # The date string was invalid
        return None

load_list函数:

def load_list(filename):
    new_list = []
    f = open("todo.txt", 'rU')
    while 1:
        line = f.readline()
        line.split(',')
        task = line[1:0]
        datetime = as_datetime(line)
        if not line:
            break
        for datetime in line:
            new_list.append(datetime)
        for task in line:
            new_list.append(task)
        return new_list

最佳答案

你必须在变量中捕获 line.split(',') 。 split 不会改变原始变量。

关于python - .split() 和 .append 来自 .txt 文件的信息作为元组到新列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22738601/

相关文章:

python - 使用 BS4 python 进行抓取

python - 具有顺序限制的两个列表的元素的排列

r - 轴标签列表中下标错误

javascript - 将 JavaScript split()-slice()-join() 序列转换为 C++

python - python 是否有一个内置函数可以为 None 获取 0

python - Matplotlib - MatplotlibDeprecationWarning

python - 压缩由0和1组成的长向量

c - 在头部被删除并重新创建后创建列表的第二个元素时出错

Javascript正则表达式分割但保留部分分隔符

regex - 用点分隔符分割 UNIX 字符串并存储在变量中