Home > Software design >  How to convert data from txt files to CSV files using python
How to convert data from txt files to CSV files using python

Time:01-14

I have a text file It is just a small example, but the real one is pretty similar.

and I want to know how to convert the TXT file to "CSV File" like this using Python?

CodePudding user response:

Read the text file contents into a list called lines.

text_file_path = r'some file path'

lines = []
with open(text_file_path, 'r') as f:
    lines = f.readlines()

You now have a list with each line in it as a string.

Create another list with the numbers for the rows.

rows = range(1, len(lines))

Now combine them as a pandas dataframe with the desired column headings and save it to csv.

import pandas as pd

csv_path = r'csv file path'

df = pd.DataFrame([rows, lines], columns = ['sr. no.', 'client'])
df.to_csv(csv_path, index=False)
  •  Tags:  
  • Related