python 2.7如何将结果写入xlsx文件

时间:2018-04-09 02:33:31

标签: python-2.7

我有一些读物:

ATCAAAGTCCCGTAGGTACGGGAAATGCAAAAAAA GGGCTAGGTAGGGATTGCCTAGTCAACTGGGGGGG TAGCTAGGTAGGGATTGCCTAGTCAACTGGCCCGG

...

...

现在,我想在每次读取的左边切12个碱基并写入文件:

f2 = open("./read1.csv","w")
with open('../001.fastq') as reader:
     for index, line in enumerate(reader):
         if index % 4 == 1:
             f2.write(line[:12]+'\n')
f2.close()

我想知道如何编写xlsx文件

2 个答案:

答案 0 :(得分:0)

每次读取都有4行

@

ATCAAAGTCCCGTAGGTACGGGAAATGCAAAAAAA

+

JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ

@

GGGCTAGGTAGGGATTGCCTAGTCAACTGGGGGGG

+

JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ

@

TAGCTAGGTAGGGATTGCCTAGTCAACTGGCCCGG

+

JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ

对于此示例,输出为:

ATCAAAGTCCCG

GGGCTAGGTAGG

TAGCTAGGTAGG

答案 1 :(得分:0)

假设您使用的是Windows并安装了Excel。 有多个库可以使用python中的Excel。我只使用win32com.client,但我很满意。我认为它默认带有anaconda,但如果没有,那么你可以从这里下载它:https://github.com/mhammond/pywin32/releases(别忘了选择合适的版本/架构)。 以下是对最重要功能的迷你参考:

from win32com.client import Dispatch  # import the necessary library

xlApp = Dispatch("Excel.Application") # starts excel
xlApp.Visible = False                 # hides window (this makes things a bit faster)
xlBook = xlApp.Workbooks.Open( fullPathToXlsx ) # opens an existing workbook

xlSheet = xlBook.Sheets(3)            # which sheet you want to use, indexing starts from 1!
print [sheet.Name for sheet in xlBook.Sheets] # if it is not the one you want you can see their order this way
xlSheet = xlBook.Sheets(sheetName)    # or you can use its name

xlSheet.Cells(row, col).Value = newValue # newValue is what you want to assign to the cell, row and col indexing starts from 1

xlApp.DisplayAlerts = False           # turns off any affirmation popup
xlBook.Save()                         # saving workbook
xlBook.SaveAs(newFullPath)            # saving as...

xlBook.Close()                        # close workbook
xlApp.Quit()                          # exit application

您可能希望在列/行索引和'字母表示之间进行转换(我的意思是左上角单元格的'A1',依此类推)。这是我用它的原因:

def cellStringToNum(aStr):
    """
    returns an excel sheet cell reference as numbers in a list as [col, row]
    """
    import string

    colS = ""
    for i in xrange(len(aStr)):
        if aStr[i] in string.ascii_uppercase:
            colS += aStr[i]
        else:
            row = int(aStr[i:])
            break
    col = 0
    for i in xrange(len(colS)):
        col += (string.ascii_uppercase.find(colS[len(colS)-1-i])+1)*(26**i)
    return [col, row]

def cellNumToString(col, row):
    import string

    colS = string.ascii_uppercase[col % 26 - 1]
    if col % 26 == 0:
        col -= 26
    else:
        col -= col % 26
    while col != 0:
        col /= 26
        colS = string.ascii_uppercase[col % 26 - 1] + colS
        if col % 26 == 0:
            col -= 26
        else:
            col -= col % 26
    return colS+str(row)

修改

但是这个问题已在这里得到解答:Python - Write to Excel Spreadsheet