Skip to main content
 首页 » 编程设计

python之如何将 xlsx 转换为制表符分隔文件

2024年10月17日9kenshinobiy

我有很多 xlsx 文件,很难将它们一个一个地转换为制表符分隔的文件

我想知道是否有任何解决方案可以通过 python 执行此操作。在这里,我发现了什么,以及如何应对失败 这是我发现并尝试了解决方案但没有用 Mass Convert .xls and .xlsx to .txt (Tab Delimited) on a Mac

我也尝试过对一个文件执行此操作以查看其工作原理但没有成功

#!/usr/bin/python 
import xlrd 
import csv 
 
 
def main(): 
    # I open the xlsx file  
    myfile = xlrd.open_workbook('myfile.xlsx') 
    # I don't know the name of sheet 
    mysheet = myfile.sheet_by_index(0) 
    # I open the output csv 
    myCsvfile = open('my.csv', 'wb') 
    # I write the file into it 
    wr = csv.writer(myCsvfile, delimiter="\t") 
    for rownum in xrange(mysheet.nrows): 
        wr.writerow(mysheet.row_values(rownum)) 
    myCsvfile.close() 
if __name__ == '__main__': 
   main() 

请您参考如下方法:

没有真正需要的主要功能。

不确定你的缩进问题,但这就是我写你所拥有的东西的方式。 (并且应该工作,根据上面的第一条评论)

#!/usr/bin/python 
import xlrd 
import csv 
 
# open the output csv 
with open('my.csv', 'wb') as myCsvfile: 
    # define a writer 
    wr = csv.writer(myCsvfile, delimiter="\t") 
 
    # open the xlsx file  
    myfile = xlrd.open_workbook('myfile.xlsx') 
    # get a sheet 
    mysheet = myfile.sheet_by_index(0) 
 
    # write the rows 
    for rownum in xrange(mysheet.nrows): 
        wr.writerow(mysheet.row_values(rownum))