user2401464
user2401464

Reputation: 537

convert a tsv file to xls/xlsx using python

I want to convert a file in tsv format to xls/xlsx..

I tried using

os.rename("sample.tsv","sample.xlsx")

But the file getting converted is corrupted. Is there any other method of doing it?

Upvotes: 7

Views: 9284

Answers (3)

HoiDam
HoiDam

Reputation: 1

import csv
from xlsxwriter.workbook import Workbook

# Add some command-line logic to read the file names.
tsv_file = 'sample.tsv'
xlsx_file = 'sample.xlsx'

# Create an XlsxWriter workbook object and add a worksheet.
workbook = Workbook(xlsx_file)
worksheet = workbook.add_worksheet()

# Create a TSV file reader.
tsv_reader = csv.reader(open(tsv_file,'rt'),delimiter="\t")

# Read the row data from the TSV file and write it to the XLSX file.
for row, data in enumerate(tsv_reader):
    worksheet.write_row(row, 0, data)

# Close the XLSX file.
workbook.close()

Upvotes: -1

jmcnamara
jmcnamara

Reputation: 41584

Here is a simple example of converting TSV to XLSX using XlsxWriter and the core csv module:

import csv
from xlsxwriter.workbook import Workbook

# Add some command-line logic to read the file names.
tsv_file = 'sample.tsv'
xlsx_file = 'sample.xlsx'

# Create an XlsxWriter workbook object and add a worksheet.
workbook = Workbook(xlsx_file)
worksheet = workbook.add_worksheet()

# Create a TSV file reader.
tsv_reader = csv.reader(open(tsv_file, 'rb'), delimiter='\t')

# Read the row data from the TSV file and write it to the XLSX file.
for row, data in enumerate(tsv_reader):
    worksheet.write_row(row, 0, data)

# Close the XLSX file.
workbook.close()

Upvotes: 10

Mike Müller
Mike Müller

Reputation: 85482

You need:

  1. Read the data from the tsv file.

  2. Convert it in what you want them to be.

  3. Write them to an Excel file with openpyxl for xlsx or xlwt for xls.

Upvotes: 1

Related Questions