Guest User

Reading a tab delimited file and output to Excel using xlwt

a guest
May 11th, 2011
1,358
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.29 KB | None | 0 0
  1. import csv
  2. import xlwt
  3. import os
  4. import sys
  5.  
  6. # Look for input file in same location as script file:
  7. inputfilename = os.path.join(os.path.dirname(sys.argv[0]), 'tabdelimited.txt')
  8. # Strip off the path
  9. basefilename = os.path.basename(inputfilename)
  10. # Strip off the extension
  11. basefilename_noext = os.path.splitext(basefilename)[0]
  12. # Get the path of the input file as the target output path
  13. targetoutputpath = os.path.dirname(inputfilename)
  14. # Generate the output filename
  15. outputfilename =  os.path.join(targetoutputpath, basefilename_noext+'.xls')
  16.  
  17. # Create a workbook object
  18. workbook = xlwt.Workbook()
  19. # Add a sheet object
  20. worksheet = workbook.add_sheet(basefilename_noext, cell_overwrite_ok=True)
  21.  
  22. # Get a CSV reader object set up for reading the input file with tab delimiters
  23. datareader = csv.reader(open(inputfilename, 'rb'),
  24.                         delimiter='\t', quotechar='"')
  25.  
  26. # Process the file and output to Excel sheet
  27. for rowno, row in enumerate(datareader):
  28.     for colno, colitem in enumerate(row):
  29.         worksheet.write(rowno, colno, colitem)
  30.  
  31. # Write the output file.
  32. workbook.save(outputfilename)
  33.  
  34. # Open it via the operating system (will only work on Windows)
  35. # On Linux/Unix you would use subprocess.Popen(['xdg-open', filename])
  36. os.startfile(outputfilename)
Advertisement
Add Comment
Please, Sign In to add comment