将TXT转换为CSV python

时间:2018-04-30 13:26:13

标签: python csv

我有一个txt数据。它看起来如下

time pos
0.02 1
0.1 2
 ...

等等。所以每一行用空格分隔。我需要将其转换为CSV文件。喜欢

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

我怎么能用python做到这一点?这就是我试过的

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

4 个答案:

答案 0 :(得分:2)

with open(filename) as infile, open('outfile.csv','w') as outfile: 
    for line in infile: 
        outfile.write(line.replace(' ',','))

答案 1 :(得分:0)

来自here

submit() { // same for 'before' and 'after'
  this.backend.methodMakingHttpRequestAndReturningObservable();
}

对于写入只使用默认选项,它会以逗号作为分隔符保存文件。

答案 2 :(得分:0)

尝试:

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

答案 3 :(得分:0)

您可以使用:

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)