This post introduces two ways to open multiple files in Python.
- “with open” # do not need to bother to close the file(s) if use “with open”
with open("datafile.csv" , "r") as f:
f.read()
with open("datafile2.csv" , "r") as f2:
f2.read()
Or
try:
with open('file.csv', 'w') as f, open('file2.csv', 'w') as f2:
do_something()
except IOError as e:
print 'Operation failed: %s' % e.strerror
- “open” # need to close the file when use open.
f = open("datafile.csv" , "r")
f2 = open("datafile2.csv" , "r")
f.read()
f2.read()
f.close()
f2.close()
References:
- Open up multiple files in a folder in python for read/write
- How can I open multiple files using “with open” in Python?