I am aware of other solutions to this problem, such as using with open as
, but first I want to understand why my code is, or is not, a good solution.
I am trying to open two CSV files, one for reading and one for writing. The script should continue only if both files were successfully opened. My code seems to accomplish that but I would like to know a couple things:
- What's the most Pythonic way to accomplish this, and why?
- Is it bad practice to exit a script from within a helper function?
Original Code:
input_file = 'in_file.csv'
output_file = 'out_file.csv'
def open_file(file, mode):
try:
fp = open(file, mode)
except IOError as e:
print "Error: cannot open {0}".format(file)
if e.errno == errno.EACCES:
print "\tPermission denied."
print "\tError message: {0}".format(e)
sys.exit()
# Not a permission error.
print "\tDoes file exist?"
print "\tError message: {0}".format(e)
sys.exit()
else:
return fp
def main():
# Open files in binary read/write mode for platform independence.
out_csv = open_file(output_file, 'wb')
in_csv = open_file(input_file, 'rb')
# Do stuff with the files
#
# with out_csv:
#
# writer = csv.writer(out_csv, delimiter='\t')
#
# with in_csv:
#
# reader = csv.reader(in_csv, delimiter='\t')
# for row in reader:
if __name__ == '__main__':
main()
Edit: Using Python 2.7.2
Edit: Draft code:
input_file = 'in_file.csv'
output_file = 'out_file.csv'
def main():
try:
with open(input_file, 'rb') as in_csv, open(output_file , 'wb') as out_csv:
writer = csv.writer(out_csv, delimiter='\t')
reader = csv.reader(in_csv, delimiter='\t')
for row in reader:
# continue processing
# many lines of code...
except IOError as e:
print "Error: cannot open {0}".format(file)
if e.errno == errno.EACCES:
print "\tPermission denied."
print "\tError message: {0}".format(e)
sys.exit()
# Not a permission error.
print "\tDoes file exist?"
print "\tError message: {0}".format(e)
sys.exit()
if __name__ == '__main__':
main()
My draft code feels a bit bloated inside the try statement (imagine 100 additional lines of code). Is there a better approach?