第一步,我们创建一个txt文件,内容为图中所示:
第二步,开始写代码:
#导入openpyxl用于excel操作from openpyxl import Workbook#新建保存结果的excel,sheetwb = Workbook(r'result.xlsx')ws = wb.create_sheet('Sheet1')#打开txt文件,把逗号替换成统一的\twith open('test.txt', 'r') as f:content = f.read().replace(',', '\t')lines = content.split('\n')for line in lines:item = line.split('\t') #保存内容ws.append(item)#print(item)#保存excel文件wb.save('result.xlsx')
第三步,执行后得到结果如下图所示: