當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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 retruns 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 retruns 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()

輸出:




相關用法


注:本文由純淨天空篩選整理自patildhanu4111999大神的英文原創作品 Convert TSV to TXT in Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。