python - 如何删除只有 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')
。现在,每次我都留下一个空白文件。
解决方案
我对你的脚本做了一些修改。我只是使用一个普通的旧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!!')
推荐阅读
- c# - 使用列表列表查询对象
- tensorflow - 在 Tensorflow 中使用矩阵乘法和 tf.layers.dense() 创建 ANN 有何不同
- node.js - 使用 Loopback 生成并发 ID
- c# - /langversion 的选项“7”无效;必须是 ISO-1、ISO-2、默认值或 1 到 6 范围内的整数
- java - 使用 Lambda 设置 OnCheckedChangeListener
- javascript - 可以 .push() 到动态命名的键吗?
- javascript - 如何动态获取执行另一个函数的函数名?
- javascript - onsubmit 问题不允许发送操作
- weblogic - 通过 WLST 的 Weblogic 部署健康状态
- flutter - 如何调整 DropdownButton 上的箭头/插入符号?