Home > OS >  Python script to process a text file and create a csv file
Python script to process a text file and create a csv file

Time:01-23

I have a text file that has data in a certain format as given below:

Name : John Doe
age  : 30
Job  : Accountant

I need this data in a csv format like :

John Doe,30,Accountant

What is the best way to process this data in python and get the desired result?

CodePudding user response:

You could try something like this:

with open('somefile.txt') as f:
    lines = f.readlines()
    print(lines)

vals = []
for line in lines:
    vals.append(line.rpartition(':')[2].strip()) <-- this would basically split your string by colon

row = ",".join(vals) <-- this is the one you can use
print(row) 

Output:

['Name : John Doe\n', 'age : 30\n', 'Job : Accountant']

John Doe,30,Accountant

Also you can write it to a csv like this:

with open('data.csv', 'w') as out:
    lines = [line for line in row.split(',')]
    my_string = ','.join(lines)
    out.write(my_string)

enter image description here

CodePudding user response:

import pandas as pd

Read in the text file

df = pd.read_csv("input.txt", delimiter='\t')

Make any necessary edits to the DataFrame

Export the DataFrame to a CSV file

df.to_csv("output.csv", index=False)

  • Related