【问题标题】:How to properly convert an XLSX file to a TSV file in Python?如何在 Python 中正确地将 XLSX 文件转换为 TSV 文件?
【发布时间】:2019-01-03 11:50:01
【问题描述】:

我正在将大型 XLSX 文件(超过 60 列和 3000 行)转换为 TSV 格式。某些字段包含带有 2-3 段的文本(多行换行符)。 我希望支持 UTF-8,并且希望每一行都显示在生成的 TSV 中的一行上

我做了以下事情:

import xlrd
import csv

# open the tsv file(output) in unicode format
with open('outTSV.tsv', 'w', encoding='utf-8') as TSVfile:
    wr = csv.writer(TSVfile, delimiter="\t")

    # open the xlsx file 
    xlfile = xlrd.open_workbook('inXLSX.xlsx')
    # retrieve sheet
    sheet = xlfile.sheet_by_index(0)

    # write rows into TSVfile
    for row in range(sheet.nrows):
        wr.writerow(sheet.row_values(row))

我希望 XLSX 文件中的每一行都转换为 TSV 文件中的一行。但是,由于某些单元格有段落,它会将它们翻译为换行符。因此我得到了变形的 TSV 文件。

XLSX 文件

变形的 TSV 文件

【问题讨论】:

  • 您将获得完全有效的 TSV 文件,带有换行符的字段包含在 " 中。你需要什么?
  • @Daniel 是的,它们包含在 " 中,但是因为我要在另一个工作流程中处理 TSV,所以我需要在一行中完成所有操作。
  • 这个 other 工作流程如何处理换行符?
  • 它读取整行并将一列映射到一个值。所以在第二行中,我相信它没有正确读取整行。
  • @Malyk “......我相信它没有正确读取整行”。你试过了吗?该条目看起来正确引用,正确的 CSV 解析器应该处理它。

标签: python csv unicode xlsx


【解决方案1】:

我能够使用 pandas 数据框解决问题。

import pandas as pd

#Read excel file into a dataframe
data_xlsx = pd.read_excel('excel.xlsx', 'Sheet1', index_col=None)

#Replace all columns having spaces with underscores
data_xlsx.columns = [c.replace(' ', '_') for c in data_xlsx.columns]

#Replace all fields having line breaks with space
df = data_xlsx.replace('\n', ' ',regex=True)

#Write dataframe into csv
df.to_csv('fileTSV.csv', sep='\t', encoding='utf-8',  index=False, line_terminator='\r\n')

【讨论】:

    猜你喜欢
    • 2013-05-27
    • 2018-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-18
    • 2022-01-17
    • 2019-05-30
    相关资源
    最近更新 更多