2017-03-04 60 views
-1
file = open("newfile.txt","w") 

file.write("Hello World") 
file.write("This is my text file") 
file.write("and the day is nice.") 
file.close() 

file= open("newfile.txt") 
lines = file.readlines() 
for i in range(len(lines)): 
    if "the" in "newfile.txt": 
     print("the") 

所以,我想要它做的是打印「the」一次,因爲「the」出現在我的文件中一次。爲什麼不這樣做?我的程序不打印任何內容(「該」)。誰能解釋爲什麼?

+4

是「」,在「newfile.txt」? – Abdou

+3

提示:「newfile.txt」中的「」檢查字符串'the'是否是字符串'newfile.txt'的一部分 – JuniorCompressor

回答

1
if "the" in "newfile.txt": 
    print("the") 

if語句驗證是否字符串文字「中的」在另一個字符串字面「newfile.txt」,這是明顯是假的,所以打印什麼。

你的目的,併爲更Python文件操作,可以考慮使用語句下面的例子:

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 

filename = 'newfile.txt' 
with open(filename, 'w') as f: 
    f.write("Hello World\n") 
    f.write("This is my text file\n") 
    f.write("and the day is nice.\n") 

with open(filename) as f: 
    for line in f.readlines(): 
     if 'the' in line: 
      print line 
0

不是"the" in "Newfile.txt",而是"the" in lines[i]

0
if "the" in "newfile.txt": 
    print("the") 

您正在覈實是否有串newfile.txt在一個子"the"

使用if "the" in file:整個文件

或者if "the" in lines[i]:,僅針對該行

0

此行是錯誤的:

if "the" in "newfile.txt": 

它試圖尋找 「」 在「newfile.txt 「字符串,不在文件中。你可能想找到它的路線,所以解決這個問題是這樣的:

if "the" in lines[i]: 

它「的」時,它發現的所有線路,並打印比較。這裏

相關問題