Jega B
Jega B

Reputation: 35

How to Convert text file to CSV in python

I need to convert text file to csv file.Below command is not working in python, which is working fine in shell prompt.Please help me to fix the issue.

subprocess.call("sed 's/[[:space:]]\+/,/g' test.txt > test.csv")

Content of test.txt

jega mca
divya BE
ramya MA

Upvotes: 1

Views: 7509

Answers (5)

Temi Fakunle
Temi Fakunle

Reputation: 982

Using the Python csv module gives better control than pandas in my opinion:

import csv

with open('txt_file.txt', 'r') as txt_file:
    # Strip out whitespace from line
    stripped_lines = [line.strip() for line in txt_file] 
    # Break up each line based on delimiter
    enlisted_lines = [line.split(' ') for line in stripped_lines if line]

    # Write lines to a CSV file using the csv package
    with open('output.csv', 'w') as csv_output:
        csv_writer = csv.writer(csv_output)
        csv_writer.writerows(enlisted_lines)

Upvotes: 0

toti08
toti08

Reputation: 2454

Here is another solution using the csv python library:

import csv
with open('test.txt', 'r') as f:
    content = f.readlines()
    with open('test.csv', 'w+',  newline = '') as csvFile:
        csvWriter = csv.writer(csvFile, delimiter = ' ')
        for elem in content:
            csvWriter.writerow([elem.strip()])

Upvotes: 0

Jean Bouvattier
Jean Bouvattier

Reputation: 365

Add shell=True

subprocess.call("sed 's/[[:space:]]\+/,/g' test.txt > test.csv", shell=True) 

Upvotes: 3

Jeril
Jeril

Reputation: 8521

You can use pandas library to do that. The following code might work:

import pandas as pd
data = pd.read_csv('test.txt', sep=" ", header=None)
df.to_csv(test.csv, sep=',')

Upvotes: 2

Crazy
Crazy

Reputation: 324

maybe use plain python:

result = ''

with open('file.txt') as f:
    result = '\n'.join(f.readlines())

with open('output.csv') as f:
    for line in result.split('\n'):
        line = line.replace(' ', ',')
        f.write(line + '\n')

Upvotes: 1

Related Questions