2012-03-09 63 views
1

我有一個.txt文件(例如test.txt)。使用python,我想在這個.txt文件中搜索字符串「100%」。請幫忙。Python:我如何在.txt文件中查找'100%'作爲字符串

 file = open('test.txt', 'r') 
     for line in file.readlines(): 
      if '100%' in line: 
       print "Successfully downloaded." 

test.txt的一部分看起來像:

6800K .......... .......... ......... .......... .......... 98%11.1M 0s 6850K .......... .......... .. ........ .......... .......... 99%10.4M 0s 6900K .......... ..... ..... .......... ..........。 100%12.6M = 2.3s

我想在這個文件中尋找'100%'。

+0

到目前爲止你做了什麼? – Jack 2012-03-09 23:48:52

+1

file = open('test.txt','r') 對於file.readlines中的行(): 如果行中包含'100 \%': print「Successfull」。 – nsh 2012-03-09 23:51:42

+0

你有什麼好,除了你需要縮進打印和放下反斜槓。 – 2012-03-09 23:55:38

回答

0

根據你所說的「搜索」,這裏有一個版本:

lines = open('file.txt').readlines() 
i = 1 
for line in lines: 
    if "100%" in line: 
     print ("Line %s:" % i), line, 
    i = i + 1 
0
with open('test.txt') as f: 
    for line in f: 
     if '100%' in line: 
      print 'found' 

with意味着,當你完成的文件,該文件被打開f,將被關閉。 for line in f依次爲你提供了每一行(並且可能比使用readlines()首先閱讀所有內容更友好)。

但是,如果您放下「\」並縮進打印,您對我看起來不錯。你會得到什麼錯誤?

+0

我沒有收到任何錯誤,但無法在文件中搜索「100%」。 – nsh 2012-03-10 00:35:49

+0

您是否刪除了「\」? – 2012-03-10 00:36:12

+0

是的,即使刪除「\」後,「100%」也沒有在文件中搜索到。 – nsh 2012-03-10 00:42:31

相關問題