Python – Convert TSV to CSV file
In this article, we will see how to Convert TSV Files to CSV using Python.
Method 1: Using Regex
TSV file can be converted into CSV file by reading one line of data at a time from TSV and replacing tab with comma using re library and writing into CSV file. We first open the TSV file from which we read data and then open the CSV file in which we write data. We read data line by line. And in each line we replace tab(“\t”) with comma(“,”) as data in CSV file is comma-separated.
Example:
Input File:
Python3
# Python program to convert .tsv file to .csv file # importing re library import re # reading given tsv file with open ( "Olympic.tsv" , 'r' ) as myfile: with open ( "Olympic.csv" , 'w' ) as csv_file: for line in myfile: # Replace every tab with comma fileContent = re.sub( "\t" , "," , line) # Writing into csv file csv_file.write(fileContent) # output print ( "Successfully made csv file" ) |
Output:
Successfully made csv file
Method 2: Using Pandas
The Pandas module provides methods that make it very easy to read data stored in a variety of overeats. Here’s a snippet of a code that converts a TSV file to a CSV file. We first read data from TSV file using read_table(). Now we write this data into a CSV file using to_csv(). Here we write index=False because when reading data with read_table() function by default it makes a new column of index starting from 0. But we don’t write it in a CSV file using index=False.
Example:
Input File:
Python3
# Python program to convert .tsv file to .csv file # importing pandas library import pandas as pd tsv_file = 'GfG.tsv' # reading given tsv file csv_table = pd.read_table(tsv_file,sep = '\t' ) # converting tsv file into csv csv_table.to_csv( 'GfG.csv' ,index = False ) # output print ( "Successfully made csv file" ) |
Output:
Successfully made csv file
Output File:
Please Login to comment...