我想将 tsv 格式的文件转换为 xls/xlsx..
我尝试使用
os.rename("sample.tsv","sample.xlsx")
但是要转换的文件已损坏。还有其他方法吗?
我想将 tsv 格式的文件转换为 xls/xlsx..
我尝试使用
os.rename("sample.tsv","sample.xlsx")
但是要转换的文件已损坏。还有其他方法吗?
这是一个使用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()
你需要:
tsv
从文件中读取数据。
将其转换为您希望它们成为的样子。
使用openpyxl forxlsx
或xlwt for将它们写入 Excel 文件xls
。
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()