Building Lists the Hard Way in Python
Just for the record, these are dumb:
# Example A: reading
file = open(somefile)
contents = []
for line in file:
contents.append(line)
# Example B: writing
file = open(somefile, \"w\")
for line in contents:
file.writeline(line)
# Example C: filtering
result = []
for line in contents:
if not line.find(\"boo\"):
result.append(line)
Python is easy. That means you should just about always be able to get the same results with a lot less effort. Python is not Java.
# Example A: reading contents = open(somefile).readlines() # Example B: writing open(somefile,\"w\").writelines(contents) # Example C: filtering result = [ line for line in contents if not line.find(\"boo\") ] # Example D: In case you miss confusing, obfuscated, ugly code since you started using python open(somefile,\"w\").writelines( [ line for line in open(otherfile) if not line.find(\"boo\") ])
By the way, example D is also stupid. Nobody should write code like that. Python is not Perl.





