ホームページ  >  記事  >  バックエンド開発  >  ステートメントを使用した Python でのファイル操作のガイド

ステートメントを使用した Python でのファイル操作のガイド

WBOY
WBOYオリジナル
2016-06-16 08:42:36965ブラウズ

以前は常にファイルを開いて、pickle.load(file) を使用して、それを処理する必要があるプロジェクトがあったためです。 。 。最後にファイルを閉じる必要があるため、少し面倒に感じられ、コードも簡潔ではありません。したがって、解決策として Python のステートメントを調べてください。

インターネット上の記事 http://effbot.org/zone/python-with-statement.htm で with を紹介しているのを見て、例を参考に理解しました。

このようなコード セグメントが頻繁にある場合は、いくつかの方法で改善できます。

コードスニペット:

set thing up
try:
  do something
except :
  handle exception
finally:
  tear thing down

ケース 1:

このような関数を今実装したい場合は、ファイルを開き、ファイルからデータを読み取り、端末に出力して、ファイルを閉じます。

論理的には「端末への印刷」は機能として独立すべきデータ処理部分として抽出できます。ファイルを開いたり閉じたりするなどの他の作業は一緒に行う必要があります。

ファイル名: for_test.txt

方法 1:

関数を使って共通部分を抽出します。

#!/usr/bin/env python 
from __future__ import with_statement  
filename = 'for_test.txt' 
def output(content): 
  print content 
#functio solution 
def controlled_execution(func): 
  #prepare thing 
  f = None 
  try: 
    #set thing up 
    f = open(filename, 'r') 
    content = f.read() 
    if not callable(func): 
      return 
    #deal with thing  
    func(content) 
  except IOError, e: 
    print 'Error %s' % str(e) 
  finally: 
    if f:  
      #tear thing down 
      f.close() 
def test(): 
  controlled_execution(output) 
test() 


方法 2:

yield を使用して、アイテムを 1 つだけ生成するジェネレーターを実装します。 for - in をループスルーします。

コードスニペットは次のとおりです:

#yield solution 
def controlled_execution(): 
  f = None 
  try: 
    f = open(filename, 'r') 
    thing = f.read() 
    #for thing in f: 
    yield thing 
  except IOError,e: 
    print 'Error %s' % str(e) 
  finally: 
    if f:  
      f.close() 
def test2(): 
  for content in controlled_execution(): 
    output(content) 

方法 3:

with で実装するにはクラスメソッドを使用します。

コードスニペットは次のとおりです:

#class solution 
class controlled_execution(object): 
  def __init__(self): 
    self.f = None 
  def __enter__(self): 
    try: 
      f = open(filename, 'r') 
      content = f.read() 
      return content 
    except IOError ,e: 
      print 'Error %s' % str(e) 
      #return None 
  def __exit__(self, type, value, traceback): 
    if self.f: 
      print 'type:%s, value:%s, traceback:%s' % \ 
          (str(type), str(value), str(traceback)) 
      self.f.close() 
def test3(): 
  with controlled_execution() as thing: 
    if thing: 
      output(thing) 
 

方法 4:

実装するには with を使用します。ただし、例外処理機能はありません。

def test4(): 
  with open(filename, 'r') as f: 
    output(f.read()) 
 
  print f.read() 

print の最後の文は、f が閉じられているかどうかをテストするために使用されます。

最後に要約すると、この記事を書く目的は主に「言語の良い機能を使用し、悪い機能は使用しないでください」という一文によって刺激されています。 Python には本当に多くのエレガントで優れた機能がありますが、道のりはまだ長く、引き続き探索していきます。 。 。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。