Convert TSV to TXT in Python
Last Updated :
16 Jan, 2022
In this article, we are going to see how to convert TSV files to text files in Python.
Approach:
- Open TSV file using open() function
- Open txt file in which we are going to write TSV file data
- Then use csv.reader() it will return a reader object which will iterate over lines in the given TSV file. (set delimiter=”\t”)
- Write data in the opened txt file line by line
- Close opened files
Syntax:
csv.reader(file_name, delimiter="\t")
Parameters:
- file_name is the input file
- delimiter is the tab separator
Example 1:
File Used:
Python3
import csv
tsv_file = open ( "Student.tsv" )
txt_file = open ( "StudentOutput.txt" , "w" )
read_tsv = csv.reader(tsv_file, delimiter = "\t" )
for row in read_tsv:
joined_string = "\t" .join(row)
txt_file.writelines(joined_string + '\n' )
txt_file.close()
|
Output:
Example 2:
File Used:
Python3
import csv
tsv_file = open ( "Downloads/Student-1.tsv" )
txt_file = open ( "Downloads/student2.txt" , "w" )
read_tsv = csv.reader(tsv_file, delimiter = "\t" )
for row in read_tsv:
joined_string = "\t" .join(row)
txt_file.writelines(joined_string + '\n' )
txt_file.close()
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...