首页 > 解决方案 > 用于读取文本文件并在 excel 中制表的 Python 程序

问题描述

0 0.303 0.775 测试集_0000.img
sm 0.524

1 0.670 0.670 测试集_0001.img
sm 2.670

我想阅读文本文件(上面的例子是 txt 文件中的数据)。我想读取大于 2.5 的 sm 值,并在 excel 表中将该 sm 值连同名称(写为 TestSet_ooxx.img)制成表格。

现在我可以读取整个文本文件并将其写入 xls 表。但我只需要在 Excel 表中写入少量信息。

标签: pythonexcelpython-2.7filetext

解决方案


打开每个文件,遍历每一行。根据行拆分后的值附加到新文件。

with open("<FILENAME>.txt") as FileObj:
    for line in FileObj:
        x = line.strip().split()[1]
        if (x > "2.5"):
            file = open("<FILENAME>.csv","a")
            file.write(line)
            file.close

推荐阅读