【问题标题】:Python, CSV, and Excel: Creating a text file with info side by sidePython、CSV 和 Excel:并排创建包含信息的文本文件
【发布时间】:2016-10-27 08:51:54
【问题描述】:

我想让这段代码创建一个文本文件,其中信息并排显示为列,但现在它显示为行。

如果你想要完整的代码,这里是我的 pastebin:

http://pastebin.com/TeD78wQn

with open('file.txt','wb') as fou:
    writer = csv.writer(fou)
    for row in data:
        writer.writerow(row)

【问题讨论】:

    标签: excel python-2.7 csv xlrd xlwt


    【解决方案1】:

    我想这就是你想要的:

    transposed = zip(*data)
    with open('col_output.txt','wb') as fou:
        writer = csv.writer(fou)
        for row in transposed:
            writer.writerow(row)
    

    编辑:要从原始数据中删除空格,只需在填充 data 时调用 .strip()

    data = []
    data.append([sheet.cell_value(row, 0).strip() for row in range(sheet.nrows)])
    data.append([sheet.cell_value(row, 1).strip() for row in range(sheet.nrows)])
    

    【讨论】:

    • 在这个原始的 excel 表上,文本之间有空格。有什么办法可以删除输出中的空间。
    • 我尝试了编辑,但没有工作。在 excel 电子表格中,一些单元格中有文本,然后它会跳过行,然后有更多带有文本的单元格。当我同时创建 excel 文件和文本文件时,其中包含这些空格。 excel文件只有空白单元格,文本文件有逗号。
    • 哦,你能以某种方式事先删除那些跳过的行吗?否则你可以在 Python 代码中跳过它们。
    • 我无法从 excel 电子表格中删除这些行,因为这些行的其他列上有有用的信息,我尝试像代码中所示添加 .strip() 但它没有改变
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-25
    • 2021-05-17
    • 2016-10-22
    • 1970-01-01
    • 2011-12-28
    • 2017-10-04
    相关资源
    最近更新 更多