简体   繁体   English

通过包含特定字符串从文件中删除行在 python 中不起作用

[英]Deleting line from file by containing a specific string is not working in python

I'm trying to delete each line which contains "annote = {" but my code is not working.我正在尝试删除包含“annote = {”但我的代码不起作用的每一行。

I have a file stored in a variable myFile and I want to go through every line of this file and delete every line which contains the string annote.我有一个文件存储在变量myFile中,我想通过该文件的每一行 go 并删除包含字符串注释的每一行。

this is basically my code:这基本上是我的代码:

    print(myFile.read())      //prints myFile
    myFile.seek(0)

    for lines in myFile:
        if b"annote = {" in lines:
            lines = lines.replace(b'.', b'')

    myFile.seek(0)
    print(myFile.read())    //this prints the exact same as the print method above so annote lines 
                            //haven't been removed from this file

I have no idea why annote lines doesn't get removed.我不知道为什么注释行没有被删除。 There is probably anything wrong with the replace method because it always is inside the if request but nothing happens with annote lines. replace 方法可能有任何问题,因为它总是在if请求中,但注释行没有任何反应。 I've also tried lines.replace(b'.', b'') instead of lines = lines.replace(b'.', b'') but nothing happened.我也尝试过lines.replace(b'.', b'')而不是lines = lines.replace(b'.', b'')但什么也没发生。

Hope anyone can help me with this problem希望任何人都可以帮助我解决这个问题

This will do it for you.这将为您完成。

f.readlines() returns a list of text lines f.readlines() 返回文本行列表

Then you check for the lines that do not contain the things you do not want然后你检查不包含你不想要的东西的行

Then you write them to a separate new file.然后将它们写入一个单独的新文件。


    f2 = open('newtextfile.txt', 'w')

    with open('text_remove_line.txt', 'r') as f:
       for line in f.readlines():
           if 'annote = {' not in line:
               f2.write(line)
    f2.close()

This should work:这应该有效:

with open('input.txt') as fin :
    lines = fin.read().split('\n')  # read the text, split into the lines

with open('output.txt', 'w') as fout :
    # write out only the lines that does not contain the text 'annote = {'
    fout.write( '\n'.join( [i for i in lines if i.find('annote = {') == -1] ))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM