如何在python中将文本文件转换为CSV

时间:2018-11-26 13:02:11

标签: python sed

我需要将文本文件转换为csv文件。下面的命令在python中不起作用,在shell提示符下工作正常。请帮助我解决此问题。

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

test.txt的内容

jega mca
divya BE
ramya MA

4 个答案:

答案 0 :(得分:2)

添加shell=True

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

答案 1 :(得分:1)

您可以使用pandas库来执行此操作。以下代码可能有效:

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

答案 2 :(得分:1)

也许使用普通的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')

答案 3 :(得分:0)

这是使用csv python库的另一种解决方案:

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