2017-03-04 3 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」を一度印刷することです。なぜそれをやっていないのですか?私のプログラムは、印刷(「the」)のために何も印刷しません。なぜ誰かが説明できますか?

+4

は「」「NEWFILE.TXT」である:あなたの目的のために

とは、次の例のようにとの声明を使用することを検討して、より多くの神託のファイル操作することが? – Abdou

+3

ヒント: "newfile.txt"の "the"は、文字列 'the'が文字列' newfile.txt'の一部であるかどうかを調べます – JuniorCompressor

答えて

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

ザ・if文は、ここでは、文字列リテラルは「」別の文字列リテラル「NEWFILE.TXT」であり、それは明らかに偽ですので、何も印刷されていないかどうかを検証します。

#!/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]。文字列newfile.txtでサブ"the"がある場合

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

あなたが検証されています。ファイル全体のため

使用if "the" in file:

あるいは、if "the" in lines[i]:、ちょうどその行の

0

この行は間違っている:

if "the" in "newfile.txt": 

それは ""「でNEWFILE.TXTを見つけようとします"文字列ではなく、ファイル内にあります。あなたは、おそらくラインでそれを見つけたいので、このようにそれを修正:

if "the" in lines[i]: 

それは、すべての行と版画「」それが見つかったと比較します。

関連する問題