简体   繁体   中英

How to write multiple python lists into an excel file using xlwt package?

I am reading a tab delimited text file into python list and now I want to have the list items into excel file. The snapshot of my text file is given below

BGIOSGA014473   0.955233    0.271947    3.5125704641    1.81252716688   Upregulated
BGIOSGA000577   0.219720    0.118096    1.86052025471   0.895706096568  Upregulated
BGIOSGA019391   0.959914    0.037380    25.67988229 4.68256668442   Upregulated
EPlOING00000022268  0.514413    0.701827    0.732962681687  -0.448188348529 Downregulated
BGIOSGA024514   0.481147    0.058495    8.22543807163   3.04009251617   Upregulated

i wanted it to be in this excel format

What I have tried is this

import xlwt
style0 = xlwt.easyxf('font: name Times New Roman, color-index red, bold on')
wb = xlwt.Workbook(encoding="utf-8")
ws = wb.add_sheet('test')

with open("out.txt") as outfile:
    for line in outfile:
        line=line.strip().split("\t")
        for i in range():
            for i,e in enumerate(line):
                ws.write(i,1,e)
wb.save('test.xls')

However, I am not getting it. I am missing how to change the row. Can anybody help

I would suggest using pandas for this. The code is as easy as

import pandas as pd

create a pandas dataframe using df = pd.DataFrame(dummy_for_data)

df.to_excel(path)

for your question:

  1. your code do not update row index
  2. ws.write() parameter is (row, col, val)
  3. range() need a argument

Here is a working sample.

import xlwt
style0 = xlwt.easyxf('font: name Times New Roman, color-index red, bold on')
wb = xlwt.Workbook(encoding="utf-8")
ws = wb.add_sheet('test')

with open("data.txt") as outfile:
    row = 0
    for line in outfile:
        line = line.strip().split("\t")
        for col, val in enumerate(line):
            ws.write(row, col, val)
        row = row + 1

wb.save('data.xls')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM