Python – Convert TSV to CSV file
Last Updated :
08 Aug, 2022
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
import re
with open ( "Olympic.tsv" , 'r' ) as myfile:
with open ( "Olympic.csv" , 'w' ) as csv_file:
for line in myfile:
fileContent = re.sub( "\t" , "," , line)
csv_file.write(fileContent)
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
import pandas as pd
tsv_file = 'GfG.tsv'
csv_table = pd.read_table(tsv_file,sep = '\t' )
csv_table.to_csv( 'GfG.csv' ,index = False )
print ( "Successfully made csv file" )
|
Output:
Successfully made csv file
Output File:
Share your thoughts in the comments
Please Login to comment...