Discuss What's the diff in the Python Programming forum on Dev Shed. What's the diff Python Programming forum discussing coding techniques, tips and tricks, and Zope related information. Python was designed from the ground up to be a completely object-oriented programming language.
Posts: 75
Time spent in forums: 1 Day 23 h 20 m 52 sec
Reputation Power: 38
The difference between "str1 == str2" and "str1 in str2" is that the former returns true if both strings are equal and the latter returns true if str1 is a substring of str2. So if str2 is "FOOhelloBAR" and str1 is "hello", then "str1 == str2" will obviously return false while "str1 in str2" will return true.
In your case the reason that the two strings are not equal is that readlines() does not strip off the newline character from the lines it reads, so Line will be equal to "mwyha\n" - not "mwyha".
Location: Woodland Hills, Los Angeles County, California, USA
Posts: 9,382
Time spent in forums: 1 Month 4 Weeks 1 Day 20 h 31 m 48 sec
Reputation Power: 4080
Instead of using readlines, you can always now read from the file object directly.
Code:
file = open('filename', 'r')
for line in file:
line = line.strip()
if line == 'mywha': print line
file.close()
or if you want to compact it a bit:
Code:
for line in open('filename', 'r'):
line = line.strip()
if line == 'mywha': print line
In this case, the file will be automatically closed and garbage collected when it falls out of scope of the for loop.
Either of these two approaches is more memory-efficient than using readlines() because they don't read the entire file into memory ahead of time, just enough chunks to get the job done.
__________________ Up the Irons
What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home. "Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
Down with Sharon Osbourne