Home > database >  Separating .txt file with Python
Separating .txt file with Python

Time:12-01

I have to separate .txt file into small pieces, based on the matched value. For example, I have .txt file looks like:

Names Age Country
Mark 19 USA
John 19 UK
Elon 20 CAN
Dominic 21 USA
Andreas 21 UK

I have to extract all rows with the same value “Age” and to copy them to other file or perfom some other action..

How it is possible to be done with Python, I have never do that before.

Thank you in advance :)

I am asking, because of I have no idea how it should be done. The excpected result is to have this data separated:

Names Age Country
Mark 19 USA
John 19 UK

Names Age Country
Elon 20 CAN

Names Age Country
Dominic 21 USA
Andreas 21 UK

CodePudding user response:

If you have them all in a list you can use something like this...

alltext = ["Names Age Country", "Mark 21 USA", "John 21 UK","Elon 20 CAN","Dominic 21 USA", "Andreas 21 UK"]

Canada = [alltext[0]] #Creates a list with your column header
NotCanada = [alltext[0]] #Creates a list with your column header

for row in alltext[1:]:
    x = row.split()
    if x[2] == "CAN":
        Canada.append(row)
    else:
        NotCanada.append(row)

print(Canada)
print(NotCanada)

Will print two different lists of your separated players.

['Names Age Country', 'Elon 20 CAN']

['Names Age Country', 'Mark 21 USA', 'John 21 UK', 'Dominic 21 USA', 'Andreas 21 UK']

CodePudding user response:

Here is a possible solution:

with open('yourfile.txt') as infile:
    header = next(infile)
    ages = {}

    for line in infile:
        name, age, country = line.rsplit(' ', 2)
        if age not in ages:
            ages[age] = []
        ages[age].append([name, age, country])

    for age in ages:
        with open(f'age-{age}.txt', 'w') as agefile:
             agefile.writeline(header)  
             agefile.writelines(ages[age])

For the sample you posted, the code above will leave you with files named age-19.txt, age-20.txt, and age-21.txt, with the contents separated by age, as you requested.

  • Related