+ 1
No output when i add a specific line, why ? - Python
Hello everyone, was writing a code that prints words from a file, I was wondering when I remove the word = file.read(), my code works just fine, but when I leave it there, the code does basically nothing or at least prints nothing can anyone explain why? Thanks in advance. def test(): file = open("words.txt","r") #word = file.read() for line in file : words = line.strip() if "z" == words[0] : print(words)
3 Réponses
+ 2
You can't read a file twice. If you read a file with 'word = file.read()', then if you try to read it again it will return an empty list.
If you keep 'word = file.read()', then intead of 'for line in file:' you should use 'for line in word:'
You can test this using this code:
gt;
f = open('words.txt')
print('first read:\n', f.read())
print('second read:\n', f.read())
<$
You'll notice the 'second read' shows nothing next to it.
+ 1
Aymane Boukrouh Okey ! thanks a lot Aymane, it make sense ! Thanks again
0
Aymane Boukrouh i tried what you suggested in using in line for word instead of for line in file, but didn't work !
i guesd it's not supposed to work at all reading it twice