3

我有这段代码可以将一些字符串打印到文本文件中,但是我需要 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,timesRead”,这就是为什么我要求python查看逗号之前的第一个字符串是否不为空。然后我看看整个项目是否不为空(不是无)。从理论上讲,我想它应该可以工作,对吧?
PS:我已经尝试询问 if 来检查“类别”是否不是“”并且不是“”,仍然是相同的结果。

4

3 回答 3

4

改为测试布尔真值,并反转您的测试,以便您确定它.split()首先会起作用,None.split()会引发异常:

if category is not None and category.split(",")[0]:

空字符串是'false-y',没有必要针对任何东西进行测试。

你甚至可以测试:

if category and not category.startswith(','):

为相同的最终结果。

从评论中,您的数据似乎有换行符。测试时把它们去掉:

for category in lastReadCategoriesList:
    category = category.rstrip('\n')
    if category and not category.startswith(','):
        lastReadCategories.write(category + '\n')
        print(category)
    else: print("/{}/".format(category))

请注意,您可以简单地category在循环内进行更改;这样可以避免.rstrip()多次调用。

于 2013-05-21T21:47:36.260 回答
1

rstrip() 您的类别,然后再将其写回文件

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.rstrip() + '\n')
    print(category.rstrip())
else: print("/" + category + "/")
lastReadCategories.close()

我能够使用您提供的示例列表对其进行测试(无需将其写入文件):

lastReadCategoriesList =  ['A,52', 'B,1\n', 'C,50', ',3']
for category in lastReadCategoriesList:
if category.split(",")[0] is not "" and category is not None:
    print(category.rstrip())
else: print("/" + category + "/")

>>> ================================ RESTART ================================
>>> 
A,52
B,1
C,50
/,3/
>>> 
于 2013-05-21T21:51:41.740 回答
0

测试空字符串(即只有空格而不是'')的经典方法是使用str.strip()

>>> st='   '
>>> bool(st)
True
>>> bool(st.strip())
False

这也适用于空字符串:

>>> bool(''.strip())
False

你有if category.split(",")[0] is not "" ...,这不是推荐的方式。你可以这样做:

if category.split(',')[0] and ...

或者,如果你想更啰嗦:

if bool(category.split(',')[0]) is not False and ...

您可能正在处理 CSV 中前导空格的问题:

>>> '    ,'.split(',')
['    ', '']
>>> '     ,val'.split(',')
['     ', 'val'] 
于 2013-05-21T21:47:13.000 回答