簡體   English   中英

打開多個文件,輔助功能

[英]Open Multiple Files, Helper Function

我知道此問題的其他解決方案, 例如with open as使用 ,但是首先我想了解為什么我的代碼是一個好的解決方案,或者不是一個好的解決方案。

我正在嘗試打開兩個CSV文件,一個用於閱讀,一個用於編寫。 僅當兩個文件都成功打開后,腳本才應繼續。 我的代碼似乎可以實現這一點,但是我想知道幾件事:

  1. 完成此操作的最Python方式是什么,為什么?
  2. 從幫助函數中退出腳本是否是不好的做法?

原始代碼:

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

您可以像這樣很容易地完成所有操作:

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

雖然@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()

要回答您的第一個觀點,您確實是對的,應該走with open as的路。 這樣做的原因是,它確保退出with語句時正確關閉了文件指針。 例如,如果在主函數中的某個地方引發了未處理的異常,則腳本將退出而不關閉文件,這很糟糕。

對於第二個問題,我認為您應該在主函數中管理Exception,以便於理解您的代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM