Reputation: 844
I have been searching for this answer but did not quite get it.
I have a text file that looks like this
who are you????
who are you man?
who are you!!!!
who are you? man or woman?
I want to skip the line with man
in it and print
who are you????
who are you!!!!
My code so far
f = open("test.txt", "r")
word = "man"
for line in f:
if word in line:
f.next()
else:
print line
This prints the first line only
who are you????
How should I troubleshoot this problem?
Thank you for your help.
Upvotes: 3
Views: 17813
Reputation: 54223
With your current code, when the current line contains "man"
:
f.next()
is already called implicitely by for line in f:
at each iteration. So you actually call f.next()
twice when "man" is found."man"
, Python will throw an exception because there's no next line.You might have been looking for continue
, which would also achieve the desired result but would be complex and unneeded. Note that it's called next
in Perl and Ruby, which might be confusing.
who are you???? # <- This line gets printed, because there's no "man" in it
who are you man? # word in line is True. Don't print anything. And skip next line
who are you!!!! # Line is skipped because of f.next()
who are you? man or woman? # word in line is True. Don't print anything.
# Try to skip next line, but there's no next line anymore.
# The script raises an exception : StopIteration
Don't forget to close the file. You can do this automatically with with
:
word = "man"
with open("test.txt") as f:
for line in f:
if not word in line:
print line, # <- Note the comma to avoid double newlines
Upvotes: 5
Reputation: 5570
It's not necessary to add an if else
statement in for
loop, so you can modify your code in this way:
f = open("test.txt", "r")
word = "man"
for line in f:
if not word in line:
print line
Furthermore, the issue in your code is that you are using f.next()
directly in a for loop used to scan the file. This is the reason because when the line contains "man" word, your code skips two lines.
If you want preserve if else
statement because this is only an example of a more complex problem, you can use the following code:
f = open("test.txt", "r")
word = "man"
for line in f:
if word in line:
continue
else:
print line
Using continue
, you skip one loop's iteration, and so you can reach your goal.
As Alex Fung suggests, would be better use with
, so your code would become like this:
with open("test.txt", "r") as test_file:
for line in test_file:
if "man" not in line:
print line
Upvotes: 5
Reputation: 51
How about
f = open("test.txt", "r")
word = "man"
for line in f:
if not word in line:
print line
Upvotes: 1