简体   繁体   中英

converting TXT to CSV python

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
with open(filename) as infile, open('outfile.csv','w') as outfile: 
    for line in infile: 
        outfile.write(line.replace(' ',','))

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.

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))

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM