python txt转xlsx
时间: 2023-09-01 09:06:43 浏览: 189
你可以使用以下代码将txt文件转换为xlsx文件:
```python
import xlwt
import pandas as pd
def txt_xls(filename, xlsname):
try:
f = open(filename, encoding="UTF-8")
xls = xlwt.Workbook()
sheet = xls.add_sheet('sheet1', cell_overwrite_ok=True)
x = 0
while True:
line = f.readline()
if not line:
break
for i in range(len(line.split(','))):
item = line.split(',')\[i\]
sheet.write(x, i, item)
x += 1
f.close()
xls.save(xlsname)
except:
raise
if __name__ == "__main__":
filename = "D:\\Python\\airpm25.txt"
xlsname = "D:\\Python\\data12.xlsx"
txt_xls(filename, xlsname)
```
这段代码将会把指定的txt文件转换为xlsx文件,并保存在指定的路径下。你只需要将`filename`和`xlsname`变量修改为你自己的文件路径即可。
#### 引用[.reference_title]
- *1* *3* [Python将txt数据转换为xls(表格)文件,方便后面做数据分析](https://blog.csdn.net/qq_44176343/article/details/111748079)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* [使用Python将TXT转为Excel](https://blog.csdn.net/zg_111/article/details/129367138)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文