Python .txt转.csv

一、代码

test.txt

sepal_len sepal_width petal_len petal_width class
5.1 3.5 1.4 0.2 0
7.0 3.2 4.7 1.4 1
6.3 3.3 6.0 2.5 2
import csv


def txt2csv(txtPath, csvPath, encoding='utf-8'):
    '''txt转csv

    :param encoding: 编码,常用'utf-8'和'GB2312'
    :return:
    '''
    csvFile = open(csvPath, 'w', newline='', encoding=encoding)
    writer = csv.writer(csvFile)
    f = open(txtPath, 'r', encoding=encoding)
    for line in f:
        csvRow = line.split()
        writer.writerow(csvRow)
    f.close()
    csvFile.close()


if __name__ == '__main__':
    txtPath = "test.txt"
    csvPath = "test.csv"
    encoding = 'utf-8'
    txt2csv(txtPath, csvPath)

二、效果

在这里插入图片描述

参考文献

如何将txt文件转化为csv文件

发布了248 篇原创文章 · 获赞 89 · 访问量 16万+

猜你喜欢

转载自blog.csdn.net/lly1122334/article/details/104426284
今日推荐