首页 > 解决方案 > 如何删除只有 CRLF 的行?

问题描述

昨天我的代码运行良好,今天它不起作用。很奇怪。我正在尝试遍历文件中的行并删除所有只有 CRLF 或只有 '#' 的行(不带引号)。

with open('C:\\my_path\\AllData.txt') as oldfile, open('C:\\Users\\my_path\\AllDataFinal.txt', 'w') as newfile:
    for line in oldfile:
        # within for loop
        line = "" if line.rstrip() in line else line
        line = "" if "#" in line else line
        newfile.write(line)
print('DONE!!')

在下面的屏幕截图中,我想删除第一行和第二行,而不是第三行。

在此处输入图像描述

我尝试了一些组合,比如rstrip()and rstrip('\n')。现在,每次我都留下一个空白文件。

标签: pythonpython-3.x

解决方案


我对你的脚本做了一些修改。我只是使用一个普通的旧replace()\r\n,并检查清理的行是否为空;

with open('test.txt') as oldfile, open('test_cleaned.txt', 'w') as newfile:
    for line in oldfile:
        # within for loop
        cleaned_line = line.replace("\r\n", "")
        if cleaned_line == '#' or cleaned_line == '':
          # Ignore the lines that are blank or are just #
          continue
        newfile.write(cleaned_line + "\n")
print('DONE!!')

推荐阅读