0
x = "mama"
with open("testing.txt") as search:
for line in search:
line = line.rstrip()
if x == line:
print line
tests.txt是一個包含Bohemian Rhapsody歌詞的文件。首先,我試圖讓它做的只是打印一行。我嘗試了幾種不同類型的設置,可以在下面看到。他們顯示爲已註釋掉,因爲我只是評論了我無法工作的所有內容。在某些時候可能還有其他代碼與其中的每個代碼一起使用,但是這些代碼分隔了我嘗試過的所有內容。在文本文件打印行中查找字符串到一個新文件Python 2.7
#searchquery = 'mama\n'
#with open('testing.txt', 'r') as f1:
# with open('616.txt', 'w') as f2:
# for line in f1:
# if line == searchquery:
# print line
# f2.write(line)
# f2.write(f1.next())
# f2.write(f2.next())
#f1.close()
#f2.close()
# -----------------------------------------------
#searchquery = 'mama\n'
#x=57
#to open the files for below I did something like:
#with open("testing.txt", r) as f1:
# with open("614.txt", w) as f2:
#while i <=x:
# if lines[i] == searchquery:
# f2.write(Lines[i])
# f2.write(Lines[i+1])
# f2.write(Lines[i+2])
# else:
# i = i+1
#
#----------------------
我只是想學習一些基礎知識。而且我確定我正在尋找某種東西。如果它在#我在這裏應付它時不關心正確的縮進。把它當作我在試圖使用這個小代碼時一直保留的筆記。
它仍然不會打印任何內容。我誠實地認爲它只是搜索第一行。 –
如果刪除'if'並只是始終打印'line',會發生什麼? –
() () () () () () () () () () () () () () () () ( ) () () () () () () () () () () () () () () () () () () () () () () () () () () () ( ) () () () () () ()它繼續...只是要完全清楚,有一些行在txt文件中有(),但沒有那麼多。 –