首页 > 解决方案 > 删除文件中所有包含`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

哈利波特在所有哈利波特的书中我们有什么不同

虽然我很喜欢这些书

比电影好

标签: pythonfile

解决方案


你的问题是你第一次使用.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()

推荐阅读