python - 无法使用 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
请建议我在哪里失踪?谢谢您的帮助。
解决方案
这里到底有什么问题?尝试以下操作:
# 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)
推荐阅读
- git - 是否可以在具有不同提交历史的两个不同遥控器(私有和公共)上维护相同的 git 项目?
- html - CSS 媒体查询未覆盖
- php - jquery没有将值发送到模式弹出窗口中的另一个输入值
- esp32 - 用 esp32 控制“ws2811”可寻址 RGB LED 灯条
- android - 我希望我的应用在 Android Studio 中的每部手机上看起来都一样
- java - 如何让 LocationManager 在后台运行?
- javascript - 如何使用 div 和 JS 在暗/亮模式之间切换?
- laravel - 根据 OAuth 令牌范围返回模型属性
- javascript - Javascript对象有什么方法可以知道它何时超出范围?
- amazon-web-services - 大约一天后 Lambda 访问 Elasticsearch 超时