如何使用Python将文本文件转换为Excel [英] How to convert a text file to Excel with Python

查看:1157
本文介绍了如何使用Python将文本文件转换为Excel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在名为DOT的文件夹中有一个文本文件(textfile.txt),我正尝试使用Python代码将该文件转换为Excel文件(Excelfile.xls).我不熟悉Python,但是从其他注释中我写了下面的代码.该代码不起作用.谁能帮助我获得正确的语法?

I have a text file (textfile.txt) in a folder called DOT and I am trying to convert that file to an Excel file (Excelfile.xls) using Python code. I am not familiar with Python but from other comments I wrote the code below. The code does not work. Could anyone help me get the correct syntax?

book = xlwt.Workbook()
import xlwt
import xlrd
f = open('/DOT/textfile.txt', 'r+')
book.save('/DOT/Excelfile' + '.xls')

推荐答案

这基于以下文档: https ://pypi.python.org/pypi/xlwt

您将需要逐行读取文件,对其进行格式化并将其写入xls文件.

You will need to read the file line by line, format it and write it to the xls file.

import xlwt
import xlrd

book = xlwt.Workbook()
ws = book.add_sheet('First Sheet')  # Add a sheet

f = open('/DOT/textfile.txt', 'r+')

data = f.readlines() # read all lines at once
for i in range(len(data)):
  row = data[i].split()  # This will return a line of string data, you may need to convert to other formats depending on your use case

  for j in range(len(row)):
    ws.write(i, j, row[j])  # Write to cell i, j

book.save('/DOT/Excelfile' + '.xls')
f.close()

在这里,数据正在被读取,所有行一次被读取.然后,将每一行拆分为数据点列表,并添加到电子表格的新行中.

Here, the data is being read, all the rows at once. Then, each line is being split into a list of data points, and added to a new row in the spreadsheet.

这不是最佳/最佳解决方案,但可以帮助您入门.如果有错误,请告诉我.

This is not the best/optimal solution but should get you started. Let me know in case there is a bug.

这篇关于如何使用Python将文本文件转换为Excel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆