티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

How to open a file using the open with statement

open with 문을 사용하여 파일을 열기

 문제 내용 

I'm looking at how to do file input and output in Python. I've written the following code to read a list of names (one per line) from a file into another file while checking a name against the names in the file and appending text to the occurrences in the file. The code works. Could it be done better?

파이썬에서 파일 입출력을 어떻게 하는지 살펴보고 있습니다. 다음 코드는 파일에서 (한 줄에 하나씩) 이름 목록을 읽어들이고 파일에 추가하여 파일 안의 이름과 매칭하는 이름을 검사하는 동안 텍스트를 추가합니다. 코드는 작동합니다. 더 좋게 작성할 수 있을까요?

 

I'd wanted to use the with open(... statement for both input and output files but can't see how they could be in the same block meaning I'd need to store the names in a temporary location.

입력 및 출력 파일 모두에 with open(...) 문을 사용하고 싶었지만 같은 블록에 있을 수 없으므로 이름을 임시 저장해야합니다.
def filter(txt, oldfile, newfile):
    '''\
    Read a list of names from a file line by line into an output file.
    If a line begins with a particular name, insert a string of text
    after the name before appending the line to the output file.
    '''

    outfile = open(newfile, 'w')
    with open(oldfile, 'r', encoding='utf-8') as infile:
        for line in infile:
            if line.startswith(txt):
                line = line[0:len(txt)] + ' - Truly a great person!\n'
            outfile.write(line)

    outfile.close()
    return # Do I gain anything by including this?

# input the name you want to check against
text = input('Please enter the name of a great person: ')    
letsgo = filter(text,'Spanish', 'Spanish2')

 

 

 높은 점수를 받은 Solution 

Python allows putting multiple open() statements in a single with. You comma-separate them. Your code would then be:

파이썬은 하나의 with에 여러 open() 문을 넣을 수 있습니다. 쉼표로 구분하면 됩니다. 코드는 다음과 같아집니다:
def filter(txt, oldfile, newfile):
    '''\
    Read a list of names from a file line by line into an output file.
    If a line begins with a particular name, insert a string of text
    after the name before appending the line to the output file.
    '''

    with open(newfile, 'w') as outfile, open(oldfile, 'r', encoding='utf-8') as infile:
        for line in infile:
            if line.startswith(txt):
                line = line[0:len(txt)] + ' - Truly a great person!\n'
            outfile.write(line)

# input the name you want to check against
text = input('Please enter the name of a great person: ')    
letsgo = filter(text,'Spanish', 'Spanish2')

 

And no, you don't gain anything by putting an explicit return at the end of your function. You can use return to exit early, but you had it at the end, and the function will exit without it. (Of course with functions that return a value, you use the return to specify the value to return.)

그리고, 아니요, 함수 끝에 명시적인 return을 추가하여 얻는 이점은 없습니다. return은 조기에 종료하기 위해 사용될 수 있지만, 당신은 이미 끝에 놓고 있고, 함수는 그렇게 종료될 것입니다. (물론 값을 반환하는 함수에서는 값을 지정하기 위해 return을 사용합니다.)

 

Using multiple open() items with with was not supported in Python 2.5 when the with statement was introduced, or in Python 2.6, but it is supported in Python 2.7 and Python 3.1 or newer.

with 문이 소개된 Python 2.5에서는 with와 함께 여러 open() 문을 사용하는 것이 지원되지 않았으며, Python 2.6에서도 지원되지 않았지만, Python 2.7 및 Python 3.1 이상에서 지원됩니다.

 

http://docs.python.org/reference/compound_stmts.html#the-with-statement http://docs.python.org/release/3.1/reference/compound_stmts.html#the-with-statement

 

If you are writing code that must run in Python 2.5, 2.6 or 3.0, nest the with statements as the other answers suggested or use contextlib.nested.

Python 2.5, 2.6 또는 3.0에서 실행해야하는 코드를 작성하는 경우, 다른 답변에서 제안한대로 with 문을 중첩하거나 contextlib.nested를 사용하세요.

 

 

 

 가장 최근 달린 Solution 

Sometimes, you might want to open a variable amount of files and treat each one the same, you can do this with contextlib

때로는 변수 수에 따라 변수의 파일을 열고 각각을 동일하게 처리해야 할 수 있습니다. 이를 contextlib으로 수행할 수 있습니다.

 

from contextlib import ExitStack
filenames = [file1.txt, file2.txt, file3.txt]

with open('outfile.txt', 'a') as outfile:
    with ExitStack() as stack:
        file_pointers = [stack.enter_context(open(file, 'r')) for file in filenames]                
            for fp in file_pointers:
                outfile.write(fp.read())                   

 

 

출처 : https://stackoverflow.com/questions/9282967/how-to-open-a-file-using-the-open-with-statement

반응형
댓글
공지사항
최근에 올라온 글