Open Multiple Files, Helper Function
我知道这个问题的其他解决方案,例如使用
我试图打开两个csv文件,一个用于读取,一个用于写入。只有当两个文件都成功打开时,脚本才能继续。我的代码似乎可以做到这一点,但我想知道以下几点:
原代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | 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() |
编辑:使用python 2.7.2
编辑:草稿代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | 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() |
我的草稿代码在try语句中感觉有点膨胀(想象一下还有100行代码)。有更好的方法吗?
虽然@inbar的答案很简单,而且工作得很好,但您可能需要花哨并实现自己的上下文管理器:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | import csv input_file = 'in_file.csv' output_file = 'out_file.csv' class csv_io: def __init__(self, input_name, output_name): # Open files in binary read/write mode for platform independence. self.input = open(input_name, 'rb') self.output = open(output_name, 'wb') def __enter__(self): return self def __exit__(self, *args): if hasattr(self, 'input'): self.input.close() if hasattr(self, 'output'): self.output.close() def main(): with csv_io(input_file, output_file) as data: writer = csv.writer(data.output, delimiter='\t') reader = csv.reader(data.input, delimiter='\t') for row in reader: do_stuff() # ...and here they are closed if __name__ == '__main__': main() |
你可以很容易地做到这一切:
1 2 3 4 5 | input_file = 'in_file.csv' output_file = 'out_file.csv' with open(input_file, 'rb') as in_csv, open(output_file , 'wb') as out_csv: # do your code |
为了回答你的第一点,你的确是对的,江户记1〔0〕是正确的。这样做的原因是,它确保在退出WITH语句时文件指针正确关闭。在您的示例中,如果在主函数中的某个地方引发了未处理的异常,则脚本将在不关闭文件的情况下退出,这很糟糕。
对于第二个问题,我认为您应该在主函数中管理异常,以便于理解您的代码。