比较字符串时遇到问题

时间:2020-03-17 14:54:20

标签: python

我有几个文件,内容如下:

562,"TEXT"
...

和其他具有以下内容的文件:

562,"NULL"
...

我正在尝试将双引号(“ TEXT”)之间的单词并写入另一个文件,但是忽略它是否为“ NULL”。

这是我的代码:

for file in os.listdir(path):
    with open(in_path, "r", encoding='utf-8') as f:
        with open(out_path, "w", encoding='utf-8') as g:
            for line in f:
                if line.startswith("562"):
                    s = line[4:].replace('"', '')
                    if s != 'NULL':
                        g.write(line[4:].replace('"', '') + "\n")

但是它不起作用,因为它总是在写值,即使它为null。我尝试将s != 'NULL'替换为s is not 'NULL',但仍然无法正常工作。任何帮助将不胜感激,谢谢。

1 个答案:

答案 0 :(得分:1)

请勿使用:

if s != 'NULL':

使用它是因为字符串s可能在行中有空格或\ n。

if 'NULL' in s:
相关问题