6

我想将 tsv 格式的文件转换为 xls/xlsx..

我尝试使用

os.rename("sample.tsv","sample.xlsx")

但是要转换的文件已损坏。还有其他方法吗?

4

3 回答 3

9

这是一个使用XlsxWriter和核心 csv 模块将 TSV 转换为 XLSX 的简单示例:

import csv
from xlsxwriter.workbook import Workbook

# Add some command-line logic to read the file names.
tsv_file = 'sample.tsv'
xlsx_file = 'sample.xlsx'

# Create an XlsxWriter workbook object and add a worksheet.
workbook = Workbook(xlsx_file)
worksheet = workbook.add_worksheet()

# Create a TSV file reader.
tsv_reader = csv.reader(open(tsv_file, 'rb'), delimiter='\t')

# Read the row data from the TSV file and write it to the XLSX file.
for row, data in enumerate(tsv_reader):
    worksheet.write_row(row, 0, data)

# Close the XLSX file.
workbook.close()
于 2013-05-31T08:46:11.000 回答
1

你需要:

  1. tsv从文件中读取数据。

  2. 将其转换为您希望它们成为的样子。

  3. 使用openpyxl forxlsxxlwt for将它们写入 Excel 文件xls

于 2013-05-31T08:31:22.140 回答
-1
import csv
from xlsxwriter.workbook import Workbook

# Add some command-line logic to read the file names.
tsv_file = 'sample.tsv'
xlsx_file = 'sample.xlsx'

# Create an XlsxWriter workbook object and add a worksheet.
workbook = Workbook(xlsx_file)
worksheet = workbook.add_worksheet()

# Create a TSV file reader.
tsv_reader = csv.reader(open(tsv_file,'rt'),delimiter="\t")

# Read the row data from the TSV file and write it to the XLSX file.
for row, data in enumerate(tsv_reader):
    worksheet.write_row(row, 0, data)

# Close the XLSX file.
workbook.close()
于 2020-08-13T02:46:53.240 回答