First, the code
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)