Open In App

Convert a TSV file to Excel using Python

A tab-separated values (TSV) file is a simple text format for storing and exchanging data in a tabular structure, such as a database table or spreadsheet data. The table’s rows match the text file’s lines. Every field value in a record is separated from the next by a tab character. As a result, the TSV format is a subset of the larger (Delimiter-Separated Values) DSV format.

In this article, we will discuss how to convert a TSV file to Excel using Python. Here we will be using XlsxWriter python module. It is used to create XLSX files. This module doesn’t come in-built with python and hence has to be installed and loaded into the working space explicitly. To install this type the below command in the terminal.



pip install XlsxWriter

Approach

Syntax:

workbook_object = WorkBook(output_filename)

Syntax:



with open(tsv_file, ‘r’) as csvfile:

…     read_tsv = csv.reader(csvfile, delimiter =’\t’)

read_tsv = csv.reader(open(tsv_file, ‘r’), delimiter=’\t’)

Syntax:

worksheet_object.write_row(row, col, data)

Syntax:

workbook_object.close()

Example 1: Convert TSV to XLS 

TSV Used:

Code:




# Importing modules
import csv
from xlsxwriter.workbook import Workbook
  
# Input file path
tsv_file = 'worldcup2014.tsv'
# Output file path
xlsx_file = 'worldcup2014.xlsx'
  
# Creating an XlsxWriter workbook object and adding 
# a worksheet.
workbook = Workbook(xlsx_file)
worksheet = workbook.add_worksheet()
  
# Reading the tsv file.
read_tsv = csv.reader(open(tsv_file, 'r', encoding='utf-8'), delimiter='\t')
  
# We'll use a loop with enumerate to pass the data 
# together with its row position number, which we'll
# use as the cell number in the write_row() function.
for row, data in enumerate(read_tsv):
    worksheet.write_row(row, 0, data)
  
# Closing the xlsx file.
workbook.close()

Output:

Example 2: Convert tsv to xls

TSV Used:

Code:




# Importing modules
import csv
from xlsxwriter.workbook import Workbook
  
# Input file path
tsv_file = 'hospital.tsv'
# Output file path
xlsx_file = 'hospital.xlsx'
  
# Creating an XlsxWriter workbook object and 
# adding a worksheet.
workbook = Workbook(xlsx_file)
worksheet = workbook.add_worksheet()
  
# Reading the tsv file.
read_tsv = csv.reader(open(tsv_file, 'r', encoding='utf-8'), delimiter='\t')
  
# We'll use a loop with enumerate to pass the 
# data together with its row position number, which
# we'll use as the cell number in the write_row()
# function.
for row, data in enumerate(read_tsv):
    worksheet.write_row(row, 0, data)
  
# Closing the xlsx file.
workbook.close()

Output:


Article Tags :