python - 删除文件中所有包含`a'的行并将其写入另一个文件
问题描述
python程序是删除文件中包含字符'a'的所有行我可以替换a但是我怎样才能删除文件中的完整行
fo=open("hp.txt","w")
fo.write("Harry Potter")
fo.write("There is a difference in all harry potter books\nWe can see it as harry grows\nthe books were written by J.K rowling ")
fo.close()
fo=open('hp.txt','r')
fi=open('writehp.txt','w')
l=fo.readlines()
for i in l:
if 'a' in i:
i=i.replace('a','')
fi.write(i)
fi.close()
fo.close()
-文件主体
--文件 hp
哈利波特所有的哈利波特书都有区别
随着哈利的成长,我们可以看到它
这些书是 JK 罗琳写的
--文件hpwrite
哈利波特在所有哈利波特的书中我们有什么不同
虽然我很喜欢这些书
比电影好
解决方案
你的问题是你第一次使用.readline()
(它只会读取一行)但你需要.readlines()
获取所有行的列表,然后i=i.replace('a','') and fi.write(i)
是错误的:
fo=open("hp.txt","w")
fo.write("Harry Potter")
fo.write("There is a difference in all harry potter books\nWe can see it as harry grows\nthe books were written by J.K rowling ")
fo.close()
fo=open('hp.txt','r')
fi=open('writehp.txt','w')
l=fo.readlines()
for i in l:
if 'a' in i:
i=i.replace('a','')
fi.write(i)
fi.close()
fo.close()
推荐阅读
- amazon-s3 - 有没有办法在恒定时间内在同一存储桶内复制 s3 上的对象 - O(1)
- jenkins - 使用 3GB 内存的 Jenkins 简单安装
- javascript - 为什么我的 Qualtrics Javascript 代码没有运行预期的迭代次数?
- javascript - 通过 JavaScript 将图像添加到 HTML 表格单元格
- c++ - vtkMolecule - 移除原子
- haskell - 如何在 Haskell 中将自然数的范围定义为字符?
- dart - BLoC 状态管理模式(Flutter)
- php - html 形式的动作脚本未正确执行
- google-speech-api - 使用 Google Cloud 文字转语音 API
- javascript - 如果我的javascript中的字符串包含'