繁体   English   中英

将TXT转换为CSV python

[英]converting TXT to CSV python

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

这里

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

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

尝试:

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

您可以使用此:

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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