无法使用python或批处理脚本删除最后一个空行

时间:2018-09-25 16:03:07

标签: python string batch-file

我的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

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

2 个答案:

答案 0 :(得分:0)

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

# 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)

答案 1 :(得分:0)

我从您的示例中获取了示例内容,其中blank.txt是最后一行为空白的文件。而output.txt文件是删除最后一个空白行后得到的新文件。

1)空白行文件

$ cat blank.txt
compponent
BO Applet
Software
Testing

$

2)删除了空白行的文件:

$ cat output.txt
compponent
BO Applet
Software
Testing
$

有效的代码:

#!/usr/bin/python3
with open("blank.txt", 'r') as f:
    lines = f.read()
    with open("output.txt", 'w') as w:
        w.write(lines[:-1])