打开多个文件,帮助程序功能

时间:2013-09-16 15:49:00

标签: python csv

我知道这个问题的其他解决方案such as using with open as,但首先我想了解为什么我的代码是或不是一个好的解决方案。

我正在尝试打开两个CSV文件,一个用于阅读,另一个用于写入。仅当两个文件都成功打开时,脚本才会继续。我的代码似乎可以实现,但我想知道几件事:

  1. 实现这一目标的最恐怖的方法是什么?为什么?
  2. 从帮助函数中退出脚本是不好的做法吗?
  3. 原始代码:

    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

    修改:草稿代码:

    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行代码)。有更好的方法吗?

3 个答案:

答案 0 :(得分:1)

你可以很容易地完成这一切:

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 :(得分:1)

虽然@ Inbar的答案很简单,并且效果很好,但您可能希望自己喜欢并实现自己的上下文管理器:

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()

答案 2 :(得分:0)

要回答你的第一点,你确实是对的,with open as是要走的路。这样做的原因是它确保在退出with语句时正确关闭文件指针。在你的例子中,如果你的main函数中的某个地方出现了未处理的异常,你的脚本将退出而不关闭文件,这是不好的。

对于第二个问题,我认为您应该在main函数中管理Exception,以便于理解您的代码。