我想将tsv格式的文件转换为xls / xlsx ..
我尝试使用
os.rename("sample.tsv","sample.xlsx")
但转换的文件已损坏。还有其他方法吗?
答案 0 :(得分:6)
以下是使用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()
答案 1 :(得分:1)
你需要:
从tsv
文件中读取数据。
按照您希望的方式对其进行转换。
将xlsx
的{{3}}或xls
的{{3}}写入Excel文件。
答案 2 :(得分:0)
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()