首页 > 解决方案 > 如何从文本文件中删除仅数字行?

问题描述

假设我有一个文本文件,其中包含字母数字值和仅逐行长度为 10 位的数值,如下所示:

abcdefgh
0123456789
edf6543jewjew
9876543219

我想删除所有仅包含那些随机 10 位数字的行,即上述示例的预期输出如下:

abcdefgh
edf6543jewjew

在 Python 3.x 中如何做到这一点?

标签: python-3.x

解决方案


with open("yourTextFile.txt", "r") as f:
    lines = f.readlines()
with open("yourTextFile.txt", "w") as f:
    for line in lines:
        if not line.strip('\n').isnumeric():
            f.write(line)
        elif len(line.strip('\n')) != 10:
            f.write(line)

推荐阅读