Wednesday, July 3, 2024
HomeLanguagesPythonConvert TSV to TXT in Python

Convert TSV to TXT in Python

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:

Calisto Chipfumbu
Calisto Chipfumbuhttp://cchipfumbu@gmail.com
I have 5 years' worth of experience in the IT industry, primarily focused on Linux and Database administration. In those years, apart from learning significant technical knowledge, I also became comfortable working in a professional team and adapting to my environment, as I switched through 3 roles in that time.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments