2

I have a txt data. it looks as follows

time pos
0.02 1
0.1 2
 ...

and so on. so the each line is separated with a space. I need to convert it in to a CSV file. like

time,pos
0.02,1
0.1,2
0.15,3

How can I do it with python ? This is what I have tried

time = []
pos = []

def get_data(filename):
    with open(filename, 'r') as csvfile:
        csvFileReader = csv.reader(csvfile)
        next(csvFileReader)
        for row in csvFileReader:
            time.append((row[0].split(' ')[0]))
            pos.append((row[1]))
    return
2
  • whats the problem in your code? Commented Apr 30, 2018 at 13:29
  • Does your file have any quoted arguments containing spaces? If not, would it suffice to just do line.replace(' ', ',')? Commented Apr 30, 2018 at 13:29

4 Answers 4

5
with open(filename) as infile, open('outfile.csv','w') as outfile: 
    for line in infile: 
        outfile.write(line.replace(' ',','))
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, more pythonic :D
you have to append \n at the end of every line
with your new edit '_io.TextIOWrapper' object has no attribute 'writeline'
I'm getting languages mixed up. It should work as it is now.
0

From here:

import csv
with open(filename, newline='') as f:
    reader = csv.reader(f, delimiter=' ')
    for row in reader:
        print(row)

For writing just use default options and it would save file with comma as a delimiter.

Comments

0

try:

import pandas as pd
with open(filename, 'r') as fo:
    data = fo.readlines()
    for d in range(len(data)):
        if d==0:
            column_headings = data[d].split()
        data_to_insert = data[d].split()
        pd.DataFrame(data_to_insert).to_excel('csv_file.csv', header=False, index=False, columns = column_headings))

1 Comment

TypeError: writelines() takes exactly one argument (0 given)
0

You can use this:

import csv
time = []
pos = []

def get_data(filename):
    with open(filename, 'r') as csvfile:
        csvfile1 = csv.reader(csvfile, delimiter=' ')
        with open(filename.replace('.txt','.csv'), 'w') as csvfile:
            writer = csv.writer(csvfile, delimiter=',')
            for row in csvfile1:
                writer.writerow(row)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.