2014-08-30 66 views
-1

我有一個名爲「list」的文件,我需要打印某些信息,但不是整個文件。我的文件如下:Python:從文件中排除某些文本

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

你必須同時檢查「/家'在線和'家庭/審計'排隊:

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'))是總是如此,只要該字符串填充

+0

阿育王奏效。我只需要將'/ home'調整爲'home /'。感謝您的答覆。在閱讀你的迴應後,對於我錯在哪裏是有道理的 – Greg 2014-08-30 08:47:55