2012-10-04 97 views
-1

我有一個包含如何使用python文件處理

"1111 1111 1111 // google 
1111 1111 1111 // google talk browser 
1111 1111 1111 // google talks 
1111 1111 1111 // google talk" 

我只想打印「//谷歌談話」的相關線(僅4號線)

試過像這樣的文件中搜索精確的字符串這不工作...

with open('file.txt', 'r') as handle: 
    for index, line in enumerate(handle, 1): 
     if line.strip() == 'talk': 
      print 'Match found on line', index 
+0

你說的「搜索準確而無需額外的字符串」是什麼意思?這個例子中你想要的輸出是什麼? –

+1

歡迎來到Stack Overflow!我們鼓勵你[研究你的問題](http://stackoverflow.com/questions/how-to-ask)。如果你已經[嘗試了某些東西](http://whathaveyoutried.com/),請將其添加到問題中 - 如果沒有,請先研究並嘗試您的問題,然後再回來。 – 2012-10-04 06:40:12

回答

3
with open('file.txt', 'r') as handle: 
    for index, line in enumerate(handle, 1): 
     if line.rstrip().endswith("// google talk") # or .endswith("talk") 
      print 'Match found on line', index 
+0

是我編輯請幫助上面的查詢 – passionTime

+0

感謝它的工作:-) – passionTime