python - 如何删除文件中不同样式的行(都是str格式)?

标签 python python-3.x

我有一个使用 python 打开的文档:

with open('my_file.txt', 'r') as fin:
    myfile = fin.readlines()

在我的文件中,我有这样的行:


     1HEE     JJ    1   3.904   5.512   1.259\n
     2HEE    CJJ    2   4.199   5.292   1.353\n
     2LLO    SJJ    3   4.367   5.234   1.445\n
     3LLO     JJ    4   4.041   4.969   1.220\n
   6.50000   6.50000  6.50000\n
 This is some other title.\n
 3\n
     1GOO    HSC    1   4.088   4.816   1.041\n
     1DDD      H    2   9.018   0.828   7.094\n
     2DDD      H    3  19.018   0.828   7.094\n

我需要保留的唯一行是这些行:


     1HEE     JJ    1   3.904   5.512   1.259\n
     2HEE    CJJ    2   4.199   5.292   1.353\n
     2LLO    SJJ    3   4.367   5.234   1.445\n
     3LLO     JJ    4   4.041   4.969   1.220\n
     1GOO    HSC    1   4.088   4.816   1.041\n
     1DDD      H    2   9.018   0.828   7.094\n
     2DDD      H    3  19.018   0.828   7.094\n

换句话说,包含来自以下信息的信息的行:

myfile[line][:44] 我必须保留。

我必须删除其他行(较短的行)。

关于如何做到这一点有什么想法吗?

最佳答案

如果必须删除的行总是少于 44 个字符,而有效行总是至少有 44 个字符(如您所说),您可以这样做:

with open('input.txt', 'r') as infile:
    with open('output.txt', 'w') as outfile:
        for line in infile:
            if len(line) >= 44:
                outfile.write(line)

关于python - 如何删除文件中不同样式的行(都是str格式)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51295280/

相关文章:

python - 使用用户输入调用特定的 python 类

python - 试图对投资金额求和,但一直说不可迭代

python - 如何从 SimpleNamespace 初始化字典?

python - Emacs Python 错误延迟

python - 如何使函数从 Python 中的函数外部获取变量?

python - 导入错误: No module named 'pkg_resources.extern.six.moves' ; 'pkg_resources.extern.six' is not a package

python - 通过for循环定义lambdas的python字典

python - 无法让我的抓取工具完成循环以用完所有关键字

python - VisibleDeprecationWarning - 这是从哪里来的?

python - 启动 robotframework-RIDE(Robot Framework IDE)时出错