Home > Mobile >  How to delete info in the middle of a txt file?
How to delete info in the middle of a txt file?

Time:04-18

so I want to delete some info inside a txt file for example: This is the txt before

[email protected]| Kristoffer Kaspersen| Cypernsvej| 30, 1| 2300 Kobenhavn| Denmark| 30935414
[email protected]| Andrew Duesbury| 1545 Portsmouth Pl| Mississauga ON L5M 7W1| Canada|  16478975695
[email protected]| Won Oh| 11149 Camarena Ave| MONTCLAIR CA 91763| United States| 9999999999

This is after

[email protected]| Kristoffer Kaspersen| Denmark| 30935414
[email protected]| Andrew Duesbury| Canada|  16478975695
[email protected]| Won Oh|United States| 99999999999

basically like deleting info between the the 2nd '|' and the 4th '|'

this was the code that I started with

f = open("Extracts.txt", "r")

x = f.readline()
print(x)
a=0
for i in x:
    if i =="|":
        a =1
        if a ==2:

here in this code I tried to count the | it did work but I wasn't quite sure how to tell the program to delete until reaching the 4th |.

CodePudding user response:

One possibility is to use split:

with open("Extracts.txt", "r") as f, open("output.txt", "w") as g:
    for line in f:
        fields = line.split('|')
        print(*fields[0:2], *fields[-2:], sep='|', end='', file=g)

output.txt:

[email protected]| Kristoffer Kaspersen| Denmark| 30935414
[email protected]| Andrew Duesbury| Canada|  16478975695
[email protected]| Won Oh| United States| 9999999999
  • Related