Open In App

Convert TSV to TXT in Python

Improve
Improve
Like Article
Like
Save
Share
Report

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




# importing library
import csv
 
# Open tsv and txt files(open txt file in write mode)
tsv_file = open("Student.tsv")
txt_file = open("StudentOutput.txt", "w")
 
# Read tsv file and use delimiter as \t. csv.reader
# function returns a iterator
# which is stored in read_csv
read_tsv = csv.reader(tsv_file, delimiter="\t")
 
# write data in txt file line by line
for row in read_tsv:
    joined_string = "\t".join(row)
    txt_file.writelines(joined_string+'\n')
 
# close files
txt_file.close()


Output:

Example 2: 

File Used:

Python3




# importing library
import csv
 
# Open tsv and txt files(open txt file in write mode)
tsv_file = open("Downloads/Student-1.tsv")
txt_file = open("Downloads/student2.txt", "w")
 
# Read tsv file and use delimiter as \t. csv.reader
# function returns a iterator
# which is stored in read_csv
read_tsv = csv.reader(tsv_file, delimiter="\t")
 
# write data in txt file line by line
for row in read_tsv:
    joined_string = "\t".join(row)
    txt_file.writelines(joined_string+'\n')
 
# close files
txt_file.close()


Output:



Last Updated : 16 Jan, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads