首页 > 解决方案 > 无法使用 python 或批处理脚本删除最后一个空白行

问题描述

我的excel文件包含:

ABC
DEF
GHI

我的要求是将以上所有行连接成单个字符串,如下所示:

ABC or DEF or GHI

下面是将 excel 行打印到文本文件中的代码。

wb = xlrd.open_workbook("abc.xlsx") 
sheet = wb.sheet_by_index(0) 
sheet.cell_value(0, 0)
with open("data.txt", "w") as dataFile:
for i in range(sheet.nrows):
    dataSet = sheet.cell_value(i, 0)
    print(dataSet, file=dataFile)

但 data.txt 文件打印为:

ABC
DEF
GHI
<---- this is a blank line ---->

所以当我使用下面的代码来连接这些行时:

with open("data.txt", "r") as data:
for each_line in data:
    try:
        objList = each_line.replace("\n", " or ")
        print(objList, end='')

    except ValueError:
        pass

这导致以下输出:

ABC or DEF or GHI or  --------->This is wrong

所需的输出是:

ABC or DEF or GHI  -------------> this is correct

请建议我在哪里失踪?谢谢您的帮助。

标签: pythonstringbatch-file

解决方案


这里到底有什么问题?尝试以下操作:

# Let's assume you have a list named contents with whatever you need to store.
contents[-1].rstrip('\n') # Removing the trailing new line symbol for the last member

with open('cmdOut', 'w', encoding='utf-8') as output:
    for line in contents:
        output.write(line)

推荐阅读