搜索特定字符串,复制到文本文件中,如果不存在,则产生错误

cha*_*ilk 0 python string copy text-files

这与我之前提出的问题类似.但我决定让它变得更复杂一些.

我正在创建一个程序,可以读取文本文件并将文本文件的特定部分复制到另一个文本文件中.但是,我也希望生成错误消息.

例如,我的文本文件如下所示:

* VERSION_1_1234
#* VERSION_2_1234
* VERSION_3_1234
#* VERSION_2_4321
Run Code Online (Sandbox Code Playgroud)

到目前为止,我的程序通过"VERSION_2"行查看并将该行复制到另一个文本文件中.

但现在,我希望它搜索"VERSION_3",如果它找到"VERSION_2"和"VERSION_3",它将产生错误.

这是我到目前为止所拥有的:

with open('versions.txt', 'r') as verFile:
    for line in verFile:
        # if pound sign, skip line
        if line.startswith('#'):
            continue
        # if version_3 there, copy
        if 'VERSION_3_' in line:
            with open('newfile.txt', 'w') as wFile:
            wFile.write(line.rpartition('* ')[-1])
        # if version_2 there, copy
        if 'VERSION_2_' in line:
            with open('newfile.txt', 'w') as wFile:
            wFile.write(line.rpartition('* ')[-1])
        # if both versions there, produce error
        if ('VERSION_3_' and 'VERSION_2_') in line:
            print ('There's an error, you have both versions in your text file')
        # if no versions there, produce error
        if not ('VERSION_3_' and 'VERSION_2_') in line:
            print ('There's an error, you don't have any of these versions in your text file')
Run Code Online (Sandbox Code Playgroud)

对不起,如果它看起来有点凌乱.但是,当我运行程序时,它按原样工作,但即使有一个VERSION_3行,它也会打印出最后两个错误消息.我不明白为什么.我做错了.

请帮忙.

Mar*_*ers 5

你的逻辑是有缺陷的; ('VERSION_3_' and 'VERSION_2_') in line不会做你认为它做的事情.

你要:

'VERSION_3_' in line and 'VERSION_2_' in line
Run Code Online (Sandbox Code Playgroud)

代替.同理:

not ('VERSION_3_' and 'VERSION_2_') in line
Run Code Online (Sandbox Code Playgroud)

应该:

'VERSION_3_' not in line and 'VERSION_2_' not in line
Run Code Online (Sandbox Code Playgroud)

表达('VERSION_3_' and 'VERSION_2_') in line,而不是可以被解释为'VERSION_2_' in line,因为任何非空字符串被认为是True在布尔上下文,所以'VERSION_3_' and 'VERSION_2_'返回只是'VERSION_2_'作为and运算符返回第二串,然后将其对被测试的in操作符:

>>> bool('VERSION_3_' and 'VERSION_2_')
True
>>> 'VERSION_3_' and 'VERSION_2_'
'VERSION_2_'
Run Code Online (Sandbox Code Playgroud)

我怀疑即使使用这些修补程序,您的代码也无法正常工作; 你一次测试一行,你的输入示例VERSION_不同的行上有字符串.