cleaning textfile each line by line ignoring few rows through python without using pandas

43 Views Asked by At

I want to use this text file in python, Read line by line, and want output as a list of lists with 9 columns (Team, Date, Rnd, A, W, D, L, Venue,Date)like:

Arsenal 2021 Rnd A W D L Venue Date R1 Tottenham 1 0 0 Emirates March R2 Man utd 0 1 0 Old Trafford March Total Average 1234 5678 Arsenal 2020 Rnd A W D L Venue Date R1 Chelsea 1 0 0 Stamford Bridge March R2 Mancity 0 1 0 Ethiad March Total Average 1234 5678 ..........and so on

|Arsenal|
| --- |
|2021|
| --- |
|Rnd|A|W|D|L|Venu|Date|
|R1|Tottenham|1|0|0|Emirates|March|
|R2|Man utd|0|1|0|Old Trafford|March|
|Total|Average|1234|5678|
| --- |
|Arsenal|
| --- |
|2020|
| --- |
|Rnd|A|W|D|L|Venu|Date|
|R1|Chelsea|1|0|0|Stamford Bridge|March|
|R2|Mancity|0|1|0|Ethiad|March|
|Total|Average|1234|5678|
| --- |
|Man Utd|
| --- |
|2021|
| --- |
|Rnd|A|W|D|L|Venu|Date|
|R1|Chelsea|1|0|0|Emirates|March|
|R2|Wolves|0|1|0|Old Trafford|March|
|Total|Average|1234|5678|
| --- |
|Man utd|
| --- |
|2020|
| --- |
|Rnd|A|W|D|L|Venu|Date|
|R1|Tottenham|1|0|0|Stamford Bridge|March|
|R2|Palace|0|1|0|Ethiad|March|
|Total|Average|1234|5678|


1

There are 1 best solutions below

0
user16603508 On

first_part = True
with open('Arsenal.txt', 'r') as fh:
    for line in fh:
        if first_part:
            word = line.rstrip('\n').rstrip('|')
            line = next(fh)
            line = next(fh)
            year = line.rstrip('\n').rstrip('|')
            line = next(fh)
            line = next(fh)
            first_part = False
        else:
            if line.startswith('|Total|'):
                first_part = True
            else:
                new_line = word + year + line
                print(new_line, end='') ````