Python:从文件中打印出某些文本

时间:2014-08-30 08:40:41

标签: python printing

我有一个名为" list"的文件。我需要打印出某些信息而不是整个文件。我的文件如下:

pool
pool/return
pool/home
pool/home/audits
pool/home/audits/2013
pool/home/audits/2014
pool/home/exchanges
pool/home/term
pool/transfers

我需要打印" / home /"除了"审核/"部分。这是我的代码:

#!/usr/bin/python
searchfile = open('list', 'r')
for line in iter(searchfile):
    if '/home' and not 'home/audits' in line:
            print line.strip()
searchfile.close()

我得到以下内容:

pool
pool/return
pool/home
pool/home/exchanges
pool/home/term
pool/transfers

但我需要它才能打印:

pool/home/exchanges
pool/home/term

1 个答案:

答案 0 :(得分:1)

你必须检查' / home'排队和家庭/审计'排队:

if '/home' in line and not 'home/audits' in line:

条件if '/home' and not 'home/audits' in line:

转换为if True and not 'home/audits' in line:

因为bool('/home')(或bool('any string'))始终为True,只要填充字符串