在Python中将 TSV 转换为 TXT
在本文中,我们将了解如何在Python中将 TSV 文件转换为文本文件。
方法:
- 使用 open()函数打开 TSV 文件
- 打开我们要在其中写入 TSV 文件数据的 txt 文件
- 然后使用 csv.reader() 它将返回一个读取器对象,该对象将遍历给定 TSV 文件中的行。 (设置分隔符=”\t”)
- 在打开的txt文件中逐行写入数据
- 关闭打开的文件
句法:
csv.reader(file_name, delimiter="\t")
参数:
- file_name 是输入文件
- delimiter 是制表符分隔符
示例 1:
使用的文件:
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()
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()
输出:
示例 2:
使用的文件:
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()
输出: