aben20807 / blog-post-issues

https://aben20807.github.io/
MIT License
9 stars 2 forks source link

Python file io #43

Open aben20807 opened 5 years ago

aben20807 commented 5 years ago

https://handyfloss.wordpress.com/2008/02/15/python-speed-vs-memory-tradeoff-reading-files/ https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects

f = open(filename,'r')
for line in f.readlines():
  if condition:
    do something
f.close()

faster:

f = open(filename,'r')
for line in f:
  if condition:
    do something
f.close()
aben20807 commented 5 years ago

work with try catch: https://stackoverflow.com/questions/7777456/python-tryexceptfinally

try:
    with open(filename, 'w') as fout:
        do something
except IOError as e:
    print("I/O error({0}): {1}".format(e.errno, e.strerror))
except:
    print("Unexpected error:", sys.exc_info()[0])