Search code examples
pythoncmdtxt

Delete every fourth line in a .txt file in Python


I have a .txt file in which I have multiple lines of code which looks like this:-

[03-Jun-22 06:32 AM] flylineman#0052
9fSQR7M1aS95wtmDpsRTvzKJzbP49dngMVn58rG2Usxo


[03-Jun-22 06:32 AM] Doughnut#6155
AM3k8ggVkRgZrYfRCnon14wy2qtbso5HYRiynwvM5eFS


[03-Jun-22 06:33 AM] Antares#4605
7apq5QKC3bmVbkWRd5ke2J9JHyidjMervc7V1joTLCPp

I want to remove the first line and then every fourth line from the file (Lines with []).
Expected Output:-

9fSQR7M1aS95wtmDpsRTvzKJzbP49dngMVn58rG2Usxo

AM3k8ggVkRgZrYfRCnon14wy2qtbso5HYRiynwvM5eFS

7apq5QKC3bmVbkWRd5ke2J9JHyidjMervc7V1joTLCPp

OS:- Windows 10

I'm a beginner so I don't know much about how to remove these, and thus not able to make a code, it would be grateful if anyone could help me:)

Thanks!


Solution

  • What about deleting every line that starts with "["?

    with open("test.txt", "r") as f:
        lines = f.readlines()
    
    with open("test.txt", "w") as f:
        for line in lines:
            if not "[" in line and line.strip() != "":
                f.write(line)