Rojo Rojo - 22 days ago 9
Python Question

Converting a text file into csv file using python

I have a requirement where in I need to convert my text files into csv and am using python for doing it. My text file looks like this ,

Employee Name : XXXXX
Employee Number : 12345
Age : 45
Hobbies: Tennis
Employee Name: xxx
Employee Number :123456
Hobbies : Football


I want my CSV file to have the column names as Employee Name, Employee Number , Age and Hobbies and when a particular value is not present it should have a value of NA in that particular place. Any simple solutions to do this? Thanks in advance

Answer

You can do something like this:

records = """Employee Name : XXXXX
Employee Number : 12345
Age : 45
Hobbies: Tennis
Employee Name: xxx
Employee Number :123456
Hobbies : Football"""

for record in records.split('Employee Name'):
    fields = record.split('\n')
    name = 'NA'
    number = 'NA'
    age = 'NA'
    hobbies = 'NA'
    for field in fields:
        field_name, field_value = field.split(':')
        if field_name == "": # This is employee name, since we split on it
            name = field_value
        if field_name == "Employee Number":
            number = field_value
        if field_name == "Age":
            age = field_value
        if field_name == "Hobbies":
            hobbies = field_value

Of course, this method assumes that there is (at least) Employee Name field in every record.