我有这段代码可以将一些字符串打印到文本文件中,但我需要python忽略每个空项,这样它就不会打印空行。
我写了这段代码,很简单,但应该做到:
lastReadCategories = open('c:/digitalLibrary/' + connectedUser + '/lastReadCategories.txt', 'w')
for category in lastReadCategoriesList:
if category.split(",")[0] is not "" and category is not None:
lastReadCategories.write(category + '\n')
print(category)
else: print("/" + category + "/")
lastReadCategories.close()
我看不出有什么问题,但是python一直在将空项打印到文件中。所有类别都是用这样的符号编写的:“category,timeread”,这就是为什么我要求python查看逗号前的第一个字符串是否不是空的。然后我看看整个项目是否不是空的(不是没有)。理论上我想应该行得通,对吧?
P、 S:我已经试过询问if来检查“category”是否不是“and not”,结果还是一样的。在
rstrip()在将类别写回文件之前
我可以用您提供的样本列表测试它(无需将其写入文件):
^{pr2}$测试空字符串(即只使用空格而不是
''
)的经典方法是使用str.strip()
:它也适用于空字符串:
^{pr2}$您有
if category.split(",")[0] is not "" ...
,这不是推荐的方法。您可以这样做:或者,如果你想说得更详细些:
您可能正在处理CSV中前导空格的问题:
请改为测试布尔真值,并反转测试,以便您确定
.split()
将首先工作,None.split()
将引发异常:空字符串是'false-y',没有必要对它进行任何测试。在
你甚至可以测试一下:
^{pr2}$为了同样的结果。在
从评论来看,你的数据中似乎出现了新行。测试时请将其剥离:
请注意,您可以在循环中简单地修改
category
;这避免了多次调用.rstrip()
。在相关问题 更多 >
编程相关推荐